How to Remove the Last Character from Each String in a List in Python?

Estimated read time 1 min read

To remove the last character from each string in a list in Python, you can use a list comprehension that slices each string up to the second-last character. Here is an example code snippet that removes the last character from each string in a list:

original_list = ["apple", "banana", "cherry", "date"]

# Remove the last character from each string
new_list = [s[:-1] for s in original_list]

print(new_list)  # Output: ['appl', 'banan', 'cherr', 'dat']

In this code, we define an original list (original_list) that contains strings.

Next, we create a new list (new_list) using a list comprehension that slices each string up to the second-last character (i.e., excludes the last character). The [:-1] syntax is used to slice the string up to the second-last character.

Finally, we print the new list (new_list) that contains each string with the last character removed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply