Python Forum
String Slicing in List Comphrensions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
String Slicing in List Comphrensions

I have a question about the following code:
Example 1
str = "hello"
i = str[2]
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!
That isn't the same thing. In the second example, i is always an int.

Possibly Related Threads…
Thread Author Replies Views Last Post
  slicing and indexing a list example leodavinci1990 4 875 Oct-12-2020, 06:39 AM
Last Post: bowlofred
  String slicing and loop iteration divyansh 9 2,573 Jun-07-2020, 10:29 PM
Last Post: divyansh
  String slicing divyansh 6 1,562 May-31-2020, 06:15 AM
Last Post: pyzyx3qwerty
  string slicing help oli_action 2 989 Mar-22-2020, 09:57 AM
Last Post: oli_action
  Help with slicing a list FWendeburg 3 1,393 Dec-02-2019, 04:57 PM
Last Post: michael1789
  Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) Drone4four 4 1,713 Aug-23-2019, 07:59 PM
Last Post: Drone4four
  string slicing default value Uchikago 1 1,465 Jul-01-2019, 11:19 AM
Last Post: perfringo
  string slicing Uchikago 2 1,314 Jun-28-2019, 06:35 AM
Last Post: perfringo
  String slicing in python from reverse ift38375 1 1,288 Apr-29-2019, 06:58 AM
Last Post: perfringo
  List slicing issue Irhcsa 3 1,620 Apr-26-2019, 09:16 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020