[英]How to get last character in string?
I want to find which word's last character is 'e' and I would like to replace 'e' with 'ing'.我想找出哪个单词的最后一个字符是'e',我想用'ing'替换'e'。 After this process want to append these in the array such as new words这个过程之后想append这些在数组里等新词
words= ['example', 'serve', 'recognize', 'ale']
for x in words:
size = len(x)
if "e" == x[size - 1]:
words.append(x.replace(x[-1], 'ing'))
print(words)
output output
['example', 'serve', 'recognize', 'ale', 'ingxampling', 'singrving', 'ringcognizing', 'aling']
I want to get the output like this我想像这样得到 output
['example', 'serve', 'recognize', 'ale', 'exampling', 'serving', 'recognizing', 'aling']
Try this:尝试这个:
words = ['example', 'serve', 'recognize', 'ale']
for x in words:
if x[-1] == 'e':
words.append(x[:-1] + 'ing')
print(words)
Or if you want a 1 liner:或者如果你想要一个 1 班轮:
words = [*words, *[x[:-1] + 'ing' for x in words if x[-1] == 'e']]
Very similar to saradartur's solution but with filtering (I also added the use of str.endswith
):与 saradartur 的解决方案非常相似,但带有过滤功能(我还添加了str.endswith
的使用):
words = ['example', 'serve', 'recognize', 'ale']
words.extend(word[:-1] + 'ing' for word in words if word.endswith('e'))
print(words)
Output Output
['example', 'serve', 'recognize', 'ale', 'exampling', 'serving', 'recognizing', 'aling']
The answer to "How to get last character in string on Python?" “如何在 Python 上获取字符串中的最后一个字符?”的答案is quite simple:很简单:
my_string = "hello"
last_char = last_char = my_string[-1:]
print(last_char)
>>> o
This can then be applied to solving what your code is trying to do:然后可以将其应用于解决您的代码尝试执行的操作:
words= ['example', 'serve', 'recognize', 'ale']
for x in words:
last_char = x[-1:]
if last_char == "e":
words.append(x[:-1]+"ing")
print(words)
>>> ['example', 'serve', 'recognize', 'ale', 'exampling', 'serving', 'recognizing', 'aling']
Looks like you don't really want to get the last character but check the last character.看起来你真的不想得到最后一个字符,而是检查最后一个字符。 Anyway, a version that can handle arbitrarily long suffixes:无论如何,一个可以处理任意长后缀的版本:
>>> suffix, replacement = 'e', 'ing'
>>> for word in words:
if word.endswith(suffix):
print(word.removesuffix(suffix) + replacement)
exampling
serving
recognizing
aling
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.