簡體   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