简体   繁体   中英

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.

You can simply use 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

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