繁体   English   中英

如何获取字符串中的最后一个字符?

[英]How to get last character in string?

我想找出哪个单词的最后一个字符是'e',我想用'ing'替换'e'。 这个过程之后想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

['example', 'serve', 'recognize', 'ale', 'ingxampling', 'singrving', 'ringcognizing', 'aling']

我想像这样得到 output

['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']]

与 saradartur 的解决方案非常相似,但带有过滤功能(我还添加了str.endswith的使用):

words = ['example', 'serve', 'recognize', 'ale']
words.extend(word[:-1] + 'ing' for word in words if word.endswith('e'))
print(words)

Output

['example', 'serve', 'recognize', 'ale', 'exampling', 'serving', 'recognizing', 'aling']

“如何在 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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