Mar-21-2019, 09:28 PM
Hello!
I have a question about the following code:
Example 1
However, when I do the same thing inside a list comprehension as below, we get a different result.
Example 2
Thanks for the assistance!
Vale
I have a question about the following code:
Example 1
str = "hello" i = str[2] str[i] TypeError: string indices must be integersSo 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