Ashley
Ashley

Reputation: 85

How should a variable be passed within format() in Python?

I am seeking to be able to use variables within the format() parentheses, in order to parameterize it within a function. Providing an example below:

sample_str = 'sample_str_{nvars}'
nvars_test = 'apple'
sample_str.format(nvars = nvars_test)  #Successful Result: ''sample_str_apple''

But the following does not work -

sample_str = 'sample_str_{nvars}'
nvars_test_2 = 'nvars = apple'
sample_str.format(nvars_test_2) # KeyError: 'nvars'

Would anyone know how to do this? Thanks.

Upvotes: 2

Views: 163

Answers (3)

Michael Ekoka
Michael Ekoka

Reputation: 20078

If you're using Python 3.6 you also have access to Python's formatted string literals.

>>> greeting = 'hello'
>>> name = 'Jane'
>>> f'{greeting} {name}'
'hello Jane'

Note that the literal expects the variables to be already present. Otherwise you get an error.

>>> f'the time is now {time}'
NameError: name 'time' is not defined

Upvotes: 0

alex
alex

Reputation: 7443

First, I'd recommend checking out the string format examples.

Your first example works as expected. From the documentation, you are permitted to actually name the thing you are passing into {}, and then pass in a same-named variable for str.format():

'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
# returns 'Coordinates: 37.24N, -115.81W'

Your second example doesn't work because you are not passing a variable called nvars in with str.format() - you are passing in a string: 'nvars = apple'.

sample_str = 'sample_str_{nvars}'
nvars_test_2 = 'nvars = apple'
sample_str.format(nvars_test_2) # KeyError: 'nvars'

It's a little more common (I think) to not name those curly-braced parameters - easier to read at least.

print('sample_str_{}'.format("apple")) should return 'sample_str_apple'.

Upvotes: 0

Ashley
Ashley

Reputation: 85

Many thanks for guidance. I did a bit more searching. For anyone who may run into the same problem, please see examples here: https://pyformat.info

sample_str = 'sample_str_{nvars}'
nvars_test_2 = {'nvars':'apple'} 
sample_str.format(**nvars_test_2)  #Successful Result: ''sample_str_apple''

Upvotes: 1

Related Questions