Reputation: 7484
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?
Upvotes: 4
Views: 6819
Reputation: 19575
Shortest way possible:
b = b.rstrip('s') + 's'
But I would write like this:
b = ''.join((b.rstrip('s'), 's'))
Upvotes: 4
Reputation: 159
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'
Upvotes: 2
Reputation: 2213
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.
Upvotes: 0
Reputation: 1124050
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'
Upvotes: 12
Reputation: 2174
def pluralize(string):
if string:
if string[-1] != 's':
string += 's'
return string
Upvotes: 2