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
  Python3 string slicing Luchano55 4 530 Feb-17-2024, 09:40 AM
Last Post: Pedroski55
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,383 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  slicing and indexing a list example leodavinci1990 4 2,286 Oct-12-2020, 06:39 AM
Last Post: bowlofred
  String slicing and loop iteration divyansh 9 4,613 Jun-07-2020, 10:29 PM
Last Post: divyansh
  String slicing divyansh 6 3,278 May-31-2020, 06:15 AM
Last Post: pyzyx3qwerty
  string slicing help oli_action 2 2,147 Mar-22-2020, 09:57 AM
Last Post: oli_action
  Help with slicing a list FWendeburg 3 2,548 Dec-02-2019, 04:57 PM
Last Post: michael1789
  Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) Drone4four 4 3,716 Aug-23-2019, 07:59 PM
Last Post: Drone4four
  string slicing default value Uchikago 1 2,780 Jul-01-2019, 11:19 AM
Last Post: perfringo
  string slicing Uchikago 2 2,329 Jun-28-2019, 06:35 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

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