alv*_*vas 478 python string join list concatenation
有没有更简单的方法将列表中的字符串项连接成一个字符串?
我可以使用该str.join()功能加入列表中的项目吗?
例如,这是输入['this','is','a','sentence'],这是所需的输出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
Run Code Online (Sandbox Code Playgroud)
Bur*_*lid 896
用途join:
>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
Run Code Online (Sandbox Code Playgroud)
6pa*_*kid 106
将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'
Run Code Online (Sandbox Code Playgroud)
小智 35
对于初学者来说,了解为什么join是一个字符串方法非常有用
一开始很奇怪,但在此之后非常有用.
join的结果总是一个字符串,但是要连接的对象可以是多种类型(生成器,列表,元组等)
.join更快,因为它只分配一次内存.比经典连接更好.扩展说明
一旦你学会了它,它就会非常舒服,你可以做这样的技巧来添加括号.
>>> ",".join("12345").join(("(",")"))
'(1,2,3,4,5)'
>>> lista=["(",")"]
>>> ",".join("12345").join(lista)
'(1,2,3,4,5)'
Run Code Online (Sandbox Code Playgroud)
Sil*_*oid 10
虽然@Burhan Khalid的回答很好,但我认为这样可以理解:
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
Run Code Online (Sandbox Code Playgroud)
join()的第二个参数是可选的,默认为"".
编辑:此功能已在Python 3中删除
小智 9
我们可以指定如何连接字符串。'-'我们可以使用' ':
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
Run Code Online (Sandbox Code Playgroud)
list_abc = ['aaa', 'bbb', 'ccc']
string = ''.join(list_abc)
print(string)
>>> aaabbbccc
string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc
string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc
string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc
Run Code Online (Sandbox Code Playgroud)
小智 5
我们也可以使用 Python 的reduce函数:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
991955 次 |
| 最近记录: |