Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maybe add extra sentence/word to string

Tags:

python

string

I've had to create code similar to this several times:

if condition():
    word = " not"
else:
    word = ""

print "A five ounce bird could{0} carry a one pound coconut".format(word)

I've stripped the problem down to its bones here, in "practice" there'd be extra variables for "A", "five", "bird", "a", "one", and "coconut" so that they might all change, and along with them, added plural s-es and whatnot.

It has always struck me as somewhat less than satisfying. The extra space required before "not" and the lack of a space before {0} both irk, but since I don't want two spaces there if word is empty, I can't see any other way to do it.

Creating two separate messages breaks with DRY and is sometimes not even viable because of the number of possible combinations.

Is there a more elegant way to do this?

like image 921
Lauritz V. Thaulow Avatar asked Jan 16 '23 14:01

Lauritz V. Thaulow


2 Answers

Create a list of words, insert if necessary, and then ' '.join(words) them.

If there are commas/periods, build a sentence structure:

[['If', 'there', 'are', 'periods'], ', ', ['build', 'a', 'sentence', 'structure'], '.']

with respective spaces in the interpunction (space after comma, space before parenthesis,…) and then ' '.join() the words within groups and ''.join() the individual groups. (Thanks to @Alfe for the suggestion with joining words and groups differently).

like image 64
eumiro Avatar answered Jan 19 '23 04:01

eumiro


Creating two separate messages breaks with DRY

If you care about i18n, then creating two separate messages is probably the only reasonable way to do it.

like image 24
NPE Avatar answered Jan 19 '23 04:01

NPE