Concatenate item in list to strings
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?
Eg 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
使用join
:
>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
将python列表转换为字符串的更通用的方法是:
>>> 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'
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)'
链接地址: http://www.djcxy.com/p/24862.html
上一篇: 计算矢量中x的值的元素数量
下一篇: 将列表中的项目连接到字符串