Python 如何获取字符串中的最后一个字符?
我想找出哪个单词的最后一个字符是“e”,我想用“ing”替换“e”。在此过程之后,您希望在数组中附加这些元素,例如新词Python 如何获取字符串中的最后一个字符?,python,Python,我想找出哪个单词的最后一个字符是“e”,我想用“ing”替换“e”。在此过程之后,您希望在数组中附加这些元素,例如新词 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) 输出 ['exam
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)
输出
['example', 'serve', 'recognize', 'ale', 'ingxampling', 'singrving', 'ringcognizing', 'aling']
我想得到这样的输出
['example', 'serve', 'recognize', 'ale', 'exampling', 'serving', 'recognizing', 'aling']
试试这个:
words = ['example', 'serve', 'recognize', 'ale']
for x in words:
if x[-1] == 'e':
words.append(x[:-1] + 'ing')
print(words)
或者,如果您想要1号班轮:
words = [*words, *[x[:-1] + 'ing' for x in words if x[-1] == 'e']]
如何在Python上获取字符串中的最后一个字符?这很简单:
my_string = "hello"
last_char = last_char = my_string[-1:]
print(last_char)
>>> o
然后,可以将其应用于解决代码试图执行的操作:
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']
看起来您不是真的想要获取最后一个字符,而是检查最后一个字符。无论如何,可以处理任意长后缀的版本:
>>> suffix, replacement = 'e', 'ing'
>>> for word in words:
if word.endswith(suffix):
print(word.removesuffix(suffix) + replacement)
exampling
serving
recognizing
aling
与saradartur的解决方案非常相似,但通过过滤,我还添加了str.endswith的用法: words=['example','serve','recognizer','ale'] words.extendedword[:-1]+如果word.endswith'e' 印刷字 输出
要获取字符串中的最后一个字符,请使用s[-1]replace替换字符串中的所有匹配字符,而不仅仅是最后一个字符。
['example', 'serve', 'recognize', 'ale', 'exampling', 'serving', 'recognizing', 'aling']