I would like to build a variable body1 use variable url1 in python 2.7
url1 = "http://somewebpage"
and body1 ={'url':url1}
give me a whitespace after the colon,
{'url': 'http://somewebpage'}
but when I use
body1 ={'url:{}'.format(url1)}
or
body1 ={'url'+':'+str(url1)}
to remove the space, it gives
set(['url:http://somewebpage'])
as the wrong output, how to avoid to be a set? what I want is just
{'url':'http://somewebpage'}
there should no space after colon.
body1 = { 'url:{}'.format(url1) }
You are creating a string through format
, then implicitly creating a set
with the {}
notation, which is syntactic sugar for the explicit set()
.
body1 = { 'url': url1 }
The {}
notation, when used with :
, implicitly creates a dictionary instead of a set, which is printed to you (for visualization purposes) as {'url': 'http://somewebpage'}
when you do print(body1)
.
You are mistaking the dictionary string representation for the string that you want to generate. You don't want to generate any data structures. You just want to format a string that by chance looks like Python's printed representation of a dictionary.
Here is what you want: body1 = "{'url':'" + url1 + "'}"
I might add, that the use case seems a bit strange to me. OP, if you're trying to create a JSON string, Python has functionality in the json
module to convert a dictionary to a JSON string with json.dumps({'url': 'http://somewebpage'})
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.