简体   繁体   中英

Most pythonic way for formatting strings

Problem:

I need to create a complex string from different parts ( nbsp = u'\\xa0', data['text'], delimeter ).

I know 3 common solutions:

res = '*{nbsp}{nbsp}{nbsp}{nbsp}{0}*{1}'.format(data['text'], delimeter, nbsp=nbsp) # seems unicode error-prone way

res = '*' + 4 * nbsp + data['text'] + '*' + delimeter

res = ''.join(['*', 4 * nbsp, data['text'], '*', delimeter])

There is another way with old % string formatting way but it looks like it becomes a legacy way.

So which one is most pythonic or may be preferable for this certain case?

Your first approach can be improved by uniformly using keyword arguments.

u'*{nbsps}{text}*{delimiter}'.format(nbsps=4*nbsp,
                                     text=data['text'],
                                     delimiter=delimiter)

The format string makes it clear that it contains three more complex blocks, each of which is defined in the same way in the arguments to unicode.format .

"Pythonic" , as I understand it, means "can be deciphered in no time after a year of not seeing the code" . I would throw the following hat in the ring:

res = "*%s%s*%s" % (4*nbsp, str(data["text"]), delimiter)

even if you consider it legacy, because it is understandable . Read it and compare it with decompiling the above suggestions.

Third one is not good solution but first two is good enough. But I prefer mixing it and trying this :

str("*"+4*"{0}"+"{1}"+"*"+"{2}").format(nbsp, data['text'], delimeter)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM