简体   繁体   中英

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

I have a string:

b = 'week'

I want to check if the last character is an "s". If not, append an "s".

Is there a Pythonic one-liner for this one?

You could use a conditional expression :

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

Personally, I'd still stick with two lines, however:

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

I know this is an old post but in one line you could write:

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

Example

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

Another solution:

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

I would still stick with the two liner but I like how 'arithmetic' this feels.

Shortest way possible:

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

But I would write like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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