Monday 12 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...