将列表中的项目连接到字符串

本文翻译自: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? 我可以使用str.join()函数吗?

Eg this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence 例如,这是输入['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

#1楼

参考:https://stackoom.com/question/qFkC/将列表中的项目连接到字符串


#2楼

Use join : 使用join

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

#3楼

Although @Burhan Khalid's answer is good, I think it's more understandable like this: 尽管@Burhan Khalid的回答很好,但我认为这样更容易理解:

from str import join

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

join(sentence, "-") 

The second argument to join() is optional and defaults to " ". join()的第二个参数是可选的,默认为“”。

EDIT: This function was removed in Python 3 编辑:此功能已在Python 3中删除


#4楼

A more generic way to convert python lists to strings would be: 将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'

#5楼

It's very useful for beginners to know why join is a string method 对于初学者来说,了解为什么join是字符串方法非常有用

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. .join更快,因为它只分配一次内存。 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)'

#6楼

We can also use the python inbuilt functionality of reduce:- 我们还可以使用reduce的python内置功能:-

from functools import reduce 从functools进口减少

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

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

print(out_str) 打印(out_str)

I hope this helps :) 我希望这有帮助 :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值