Jesper - jtk.eth
Jesper - jtk.eth

Reputation: 7484

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?

Upvotes: 4

Views: 6819

Answers (6)

renatodamas
renatodamas

Reputation: 19575

Shortest way possible:

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

But I would write like this:

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

Upvotes: 4

Abdelhak
Abdelhak

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

LoicM
LoicM

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

Martijn Pieters
Martijn Pieters

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

User2342342351
User2342342351

Reputation: 2174

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

    return string

Upvotes: 2

Copy and Paste
Copy and Paste

Reputation: 526

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

Upvotes: 1

Related Questions