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.