SMTH
SMTH

Reputation: 95

Can't convert a string to a customized one using f-Strings

I'm trying to create params using some values dynamically, so I tried to use f-Strings. However, i can't achieve what I expect to have.

If I use the following values:

lat = '13715482'
lon = '6320767'
some_id = '7783' 

within the params below:

parameter = {'lat':f'{lat}','lon':f'{lon}','spatRef':{'spat_id':f'{some_id}'}}

I get output like:

{'lat': '13715482', 'lon': '6320767', 'spatRef': {'spat_id': '7783'}}

However, what I'm trying to get is (notice the two double quotes around the whole string):

"{'lat': '13715482', 'lon': '6320767', 'spatRef': {'spat_id': '7783'}}"

How can I get that?

Upvotes: 1

Views: 61

Answers (2)

schlöpp
schlöpp

Reputation: 181

I think you're searching for str()

lat = '13715482'
lon = '6320767'
some_id = '7783'

parameter = str(
  {
    'lat': lat,
    'lon': lon,
    'spatRef': {
      'spat_id': some_id
    }
  }
)

To use this with quotes around it you could use this:

print(f'{parameter!r}')
>>> "{'lat': '13715482', 'lon': '6320767', 'spatRef': {'spat_id': '7783'}}"

This uses the string's __repr__

Upvotes: 1

Albin Paul
Albin Paul

Reputation: 3419

You need internal representation of the string that is printed and for that we can use the repr function.

lat = '13715482'
lon = '6320767'
some_id = '7783' 
parameter = {'lat':f'{lat}','lon':f'{lon}','spatRef':{'spat_id':f'{some_id}'}}
print(repr(str(parameter)))

OUTPUT

C:\Users\albin\Documents\codebase> python3 test.py
"{'lat': '13715482', 'lon': '6320767', 'spatRef': {'spat_id': '7783'}}"

Upvotes: 1

Related Questions