[Tutor] Merge a dictionary into a string
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Mar 16 14:09:17 EDT 2019
On 16/03/2019 17:39, Valerio Pachera wrote:
> I wish to get a single string like this:
>
> 'a "hallo" b "world"'
>
> Notice I wish the double quote to be part of the string.
> In other words I want to wrap the value of a and b.
When dealing with string layouts I tend to go to
string formatting...
>>> d= {'a':"alpha",'b':"beta"}
>>> ' '.join(['{} "{}"'.format(k,v) for k,v in d.items()])
'a "alpha" b "beta"'
>>>
Or using old C style formatting, it's very slightly shorter:
>>> ' '.join(['%s "%s"'% (k,v) for k,v in d.items()])
'a "alpha" b "beta"'
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list