Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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?

like image 991
jesperk.eth Avatar asked Dec 06 '22 18:12

jesperk.eth


1 Answers

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'
like image 165
Martijn Pieters Avatar answered May 24 '23 05:05

Martijn Pieters