Python Forum
String Slicing in List Comphrensions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: String Slicing in List Comphrensions (/thread-16959.html)



String Slicing in List Comphrensions - Patroclus72790 - Mar-21-2019

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


RE: String Slicing in List Comphrensions - nilamo - Mar-21-2019

That isn't the same thing. In the second example, i is always an int.