簡體   English   中英

在字符串末尾插入字符的最 Pythonic 和有效的方法(如果還沒有的話)

[英]Most Pythonic and efficient way to insert character at end of string if not already there

我有一個字符串:

b = 'week'

我想檢查最后一個字符是否是“s”。 如果不是,請附加一個“s”。

這個有沒有 Pythonic one-liner?

您可以使用條件表達式

b = b + 's' if not b.endswith('s') else b

就個人而言,我仍然堅持兩行,但是:

if not b.endswith('s'):
    b += 's'
def pluralize(string):
    if string:
        if string[-1] != 's':
            string += 's'

    return string
b = b + 's' if b[-1:] != 's' else b

我知道這是一篇舊帖子,但您可以在一行中寫道:

b = '%ss' % b.rstrip('s')

示例

>>> string = 'week'
>>> b = '%ss' % string.rstrip('s')
>>> b
'weeks'

另一種解決方案:

def add_s_if_not_already_there (string):
     return string + 's' * (1 - string.endswith('s'))

我仍然會堅持使用兩個班輪,但我喜歡這種“算術”的感覺。

可能的最短方式:

b = b.rstrip('s') + 's'

但我會這樣寫:

b = ''.join((b.rstrip('s'), 's'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM