简体   繁体   中英

How to remove the first and last letter of a string?

I'd like to remove the first and last letter from a string. So far I've made something like this:

string = "wildcatatewonderfulcake"
first_letter_remvoer = string.strip(string[0])
print(first_letter_remvoer)
second_letter_remover = first_letter_remvoer.strip(string[-1])
print(second_letter_remover)

But sadly if the first letter is for example 'c' and 'c' exists more then once in a given string, it deletes every single 'c' from the string. Same goes with the last letter.

Strip removes all instances of the letter from the start and end of a string until it encounters a character that isn't expected to be stripped, you can just slice

string[1:-1]

Otherwise you can use removesuffix/prefix

string.removesuffix(string[-1]).removeprefix(string[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM