I created a dictionary for peoples' names as such:
names = {"first": , "second": , "third":}
What I want to do is call each name and combine them as a string, being separated by a plus sign. Below is a tedious way of doing it:
str(names["first"]) + "+" + str(names["second"]) + "+" + str(names["third"])
This line is from a larger module I am attempting to create. I tried to following for simplicity, but it resulted in a syntax error:
str(names["first"] "%+d" + names["second"] "%+d" + names["third"])
Is there a way of simplifying the above so that it prints:
firstname+secondname+thirdname
In python 2 you have to use the slightly hacky
"{first}+{second}+{third}".format(**names)
However, as GingerPlusPlus points out, in python 3 you can get away from this **kwargs
chicanery and instead use format_map
"{first}+{second}+{third}".format_map(names)
如果可以使用namedtuple
而不是dict
来存储名称,则建议:
'+'.join(map(str, names))
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.