3

Is it possible using python's string format to conditionally include additional characters along with the string variable only if the variable is not empty?

>>> format_string = "{last}, {first}"
>>> name = {'first': 'John', 'last':'Smith'}
>>> format_string.format(**name)
'Smith, John' # great!
>>> name = {'first': 'John', 'last':''}
>>> format_string.format(**name)
', John' # don't want the comma and space here, just 'John'

I would like to use the sameformat_string variable to handle any combination of empty or non-empty values for first or last in the name dict.

What's the easiest way to do this in python?

3 Answers 3

6

Why don't you use strip():

>>> format_string = "{last}, {first}"
>>> name = {'first': 'John', 'last':''}
>>> format_string.format(**name).strip(', ')
>>> 'John'
Sign up to request clarification or add additional context in comments.

3 Comments

strip() would remove it from the first version as well ("SmithJohn"), so I'd still need some kind of if structure.
No it will not. Have you tested it? Strip only removes leading and trailing characters.
No I didn't test it and yes it does work. I guess I forgot strip() only happens at the ends of the string. Thanks.
1

You can set value for separator based on condition.

'{first}{separator}{last}'.format(**{"first":first, "last":last,"separator":(", " if last and first else "")})

Comments

0

You could run the original dict through a function to 'clean' it, adding commas where appropriate. Or, have a defaultdict.

The following solution, the simplest, does a post-process step to remove any extra commas and spaces:

source

import re

name = {'first': 'John', 'last':''}
format_string = '{last}, {first}'

def fixme(instr):
    return re.sub('^, ', '',
                  re.sub(', $', '',
                         instr))

print fixme(format_string.format(**dict(first='John', last='')))
print
print fixme(format_string.format(**dict(first='', last='Smith')))

output

John

Smith

1 Comment

Keep in mind that this solution scales exponentially.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.