Python Forum

Full Version: String Slicing in List Comphrensions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

I have a question about the following code:
Example 1
str = "hello"
i = str[2]
str[i]
TypeError: string indices must be integers
So the result is as expected: When you attempt to slice a string with a string, you get a type error.

However, when I do the same thing inside a list comprehension as below, we get a different result.

Example 2
result = [str[:i] + str[i].upper() + str[i+1:] for i in range(len(str))]
['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']
Why does this happen? My guess is that slicing might function differently when used in a list comprehension, but this has been giving me a headache for some time this afternoon.

Thanks for the assistance!
Vale
That isn't the same thing. In the second example, i is always an int.