Python Forum
String Slicing in List Comphrensions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
String Slicing in List Comphrensions
#1
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
Reply
#2
That isn't the same thing. In the second example, i is always an int.
Reply


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

Forum Jump:

User Panel Messages

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