Concatenate item in list to strings

2018-12-31 04:20发布

Is there a simpler way to concatenate string items in list into a single string?

Can I use the str.join() function to join items in list?

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

5条回答
流年柔荑漫光年
2楼-- · 2018-12-31 04:28

Although @Burhan Khalid's answer is good, I think it's more understandable like this:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

The second argument to join() is optional and defaults to " ".

EDIT: This function was removed in Python 3

查看更多
素衣白纱
3楼-- · 2018-12-31 04:29

We can also use the python inbuilt functionality of reduce:-

from functools import reduce

sentence = ['this','is','a','sentence']

out_str=str(reduce(lambda x,y:x+"-"+y,sentence))

print(out_str)

I hope this helps :)

查看更多
零度萤火
4楼-- · 2018-12-31 04:35

Use join:

>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
查看更多
深知你不懂我心
5楼-- · 2018-12-31 04:36

A more generic way to convert python lists to strings would be:

>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
'12345678910'
查看更多
像晚风撩人
6楼-- · 2018-12-31 04:42

It's very useful for beginners to know why join is a string method

It's very strange at the beginning, but very useful after this.

The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc)

.join is faster because it allocates memory only once. Better than classical concatenation. extended explanation

Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.

  >>> ",".join("12345").join(("(",")"))
  '(1,2,3,4,5)'

  >>> lista=["(",")"]
  >>> ",".join("12345").join(lista)
  '(1,2,3,4,5)'
查看更多
登录 后发表回答