简体   繁体   中英

is there a more 'pythonic' way to generate a string from a list with customized separators

I am wondering if there is a more pythonic way to generate a string from a list than the one below that works.

Disclaimer: I am a biophysicist, with not an advanced knowledge of python and did search it and test combinations like: resid {} or .format(a) / ([a]) / (*a) / (x for x in a) extensively, but probably I do not know what to look for... I know the code below works, but I do not clearly understand why any of the listed does not.

input:

a=[23,33,105,400]

Code:

c=""
for x in a[0:-1]: 
     c = c + "resid {} or ".format(x)
c=c+"resid {}".format(a[-1])
print(c)

output:

resid 23 or resid 33 or resid 105 or resid 400

Use string-joining

" or ".join("resid {}".format(x) for x in [23,33,105,400])
# 'resid 23 or resid 33 or resid 105 or resid 400'

You can also use f-strings

" or ".join(f'resid {x}' for x in [23,33,105,400])

You can create a format string as follows:

format_string = (len(a)-1) * 'resid {} or ' + 'resid {} '

then apply a to it by:

print(format_string.format(*a))

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