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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With