简体   繁体   English

将列表更改为具有特定格式的字符串

[英]Change a list to a string with specific formatting

Let's say that I have a list of names: 假设我有一个名称列表:

names = ['john', 'george', 'ringo', 'paul']

And need to get a string output like: 并需要获得类似以下的字符串输出:

john', 'george', 'ringo', 'paul

(Note that the missing quote at the beginning and at the end is on purpose) (请注意,开头和结尾处缺少的报价是有意的)

Is there an easier way to do this than 有没有比这更简单的方法

new_string=''
for x in names:
    new_string = new_string + x + "', '"

I know something like that will work, however the real names list will be very very (very) big and was wondering if there is a nicer way to do this. 我知道类似的方法会起作用,但是真实names列表会非常非常大,并且想知道是否有更好的方法可以做到这一点。

You can simply use str.join : 您可以简单地使用str.join

>>> names = ['john', 'george', 'ringo', 'paul']
>>> print("', '".join(names))
john', 'george', 'ringo', 'paul
>>>

may be bad way to do it, just wana share it : 可能是不好的方法,只想分享一下:

>>> names = ['john', 'george', 'ringo', 'paul']
>>> print(str(names)[2:-2])
john', 'george', 'ringo', 'paul

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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