首页 文章

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

提问于
浏览
322

有没有更简单的方法将列表中的字符串项连接成一个字符串?

我可以使用 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

5 回答

  • 26

    使用join

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

    将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'
    
  • 9

    这对初学者来说非常有用why join is a string method

    一开始很奇怪,但在此之后非常有用 .

    join的结果总是一个字符串,但是要连接的对象可以是多种类型(生成器,列表,元组等)

    .join 更快,因为它只分配一次内存 . 比经典连接更好 . extended explanation

    一旦你学会了它,它就会非常舒服,你可以做这样的技巧来添加括号 .

    >>> ",".join("12345").join(("(",")"))
      '(1,2,3,4,5)'
    
      >>> lista=["(",")"]
      >>> ",".join("12345").join(lista)
      '(1,2,3,4,5)'
    
  • 655

    虽然@Burhan Khalid's answer很好,但我认为这样可以理解:

    from str import join
    
    sentence = ['this','is','a','sentence']
    
    join(sentence, "-")
    

    join()的第二个参数是可选的,默认为“” .

    编辑:此功能已在Python 3中删除

  • 0

    我们还可以使用python内置的reduce功能: -

    来自functools import reduce sentence = ['this','is','a','sentence'] out_str = str(reduce(lambda x,y:x“ - ”y,sentence))print(out_str)

    我希望这有帮助 :)

相关问题