Monday, August 12, 2019

python - Concatenate item in list to strings



Is there a simpler way to concatenate string items in a list into a single string? Can I use the str.join() function?




E.g. this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence



sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str

Answer




Use join:



>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...