Search code examples
pythonpython-3.xf-string

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?


Solution

  • 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__