【问题标题】:How to concatenate (join) items in a list to a single string如何将列表中的项目连接(加入)到单个字符串
【发布时间】:2023-02-06 22:03:40
【问题描述】:

如何将字符串列表连接成单个字符串?

例如,给定['this', 'is', 'a', 'sentence'],我如何得到"this-is-a-sentence"


用于处理一些字符串单独的变量,请参阅How do I append one string to another in Python?

对于相反的过程——从字符串创建列表——请参阅How do I split a string into a list of characters?How do I split a string into a list of words?

【问题讨论】:

    标签: python string list concatenation


    【解决方案1】:

    使用str.join

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

    【讨论】:

    • 不明白,左边的'-'应该是什么?
    • @LawrenceDeSouza 您要加入的字符串;请参阅 documentationthis answer,其中更详细一些。
    • 我有点希望 sentence.join(" ") 也能工作,因为反向操作是 list.split(" ")。知道这是否会被添加到 Python 的列表方法中吗?
    • @Wouter,不会。一方面,只能连接字符串列表;所以 list.join 不适合任意列表。另一方面,str.join 的参数可以是任何“可迭代”的字符串序列,而不仅仅是一个列表。唯一有意义的是内置函数join(list, sep);如果您真的需要,在(基本上已过时的)string 模块中有一个。
    • @alexis 这确实有道理,Python 列表可以包含混合类型的元素,而且它并不总是可以连接的。谢谢!
    【解决方案2】:

    将列表转换为字符串的更通用的方法(也包括数字列表)是:

    >>> 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
    

    【讨论】:

    • 为什么当输入是字符串时需要列表理解?另外 map(str, my_lst) 就足够了,无需枚举列表 =)
    • 这个问题的大部分答案都在考虑列表中有字符串的情况。我的是将列表转换为字符串的通用方法。在我的示例中,列表的类型为 int,但它可以是任何可以表示为字符串的类型。
    • 此外,map 在与 lambda 函数一起使用时也很有用。例如 ' '.join(map(lambda x: ' $'+ str(x), my_lst)) 将返回 '$1 $2 $3 $4 $5 $6 $7 $8 $9 $10'
    • 添加地图实际上有助于处理除字符串之外的数据类型。伟大的!
    【解决方案3】:

    对新手了解很有用 why join is a string method

    一开始很奇怪,但在这之后非常有用。

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

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

    一旦你学会了,它会很舒服,你可以做这样的技巧来添加括号。

    >>> ",".join("12345").join(("(",")"))
    Out:
    '(1,2,3,4,5)'
    
    >>> list = ["(",")"]
    >>> ",".join("12345").join(list)
    Out:
    '(1,2,3,4,5)'
    

    【讨论】:

    • 有人可以解释第二个join()join(("(",")")) 的作用吗?就像魔术一样
    • ("(",")") 是两个字符串的元组 - 左括号 "(" 和右括号 ")"。因此,第二个 join() 使用第一个 join() 的输出作为分隔符(即 '1,2,3,4,5')来连接这两个字符串。
    • 它是否正确? “连接的结果始终是一个字符串,但要连接的对象可以是多种类型(生成器、列表、元组等)。” Aaron S 的回答表明这不是真的,如果列表中还有其他类型,则必须使用 map(str, ) 。
    • @O'Rooney 的回答是你可以 .join 列表、元组或生成器,它们是不同类型的集合,但它们应该只包含字符串。
    【解决方案4】:

    从未来编辑: 请不要使用下面的答案。此函数在 Python 3 中被删除,Python 2 已死。即使您仍在使用 Python 2,您也应该编写 Python 3 就绪代码,以使不可避免的升级变得更容易。


    虽然@Burhan Khalid's answer很好,但我觉得这样更容易理解:

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

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

    【讨论】:

    • This function is deprecated in 2.x and going to be removed in 3.x. 既然如此,我不建议在提供的其他答案中使用它。
    • @Mathew Green 这个答案和 Burhan Khalid 的答案以不同的方式使用相同的功能,所以他的答案也被弃用了。但感谢您指出这一点,我得弄清楚如何加入 3.x。但如果您使用的是 2.x,它就不会消失。
    • 虽然他没有被弃用。您的建议使用了 Lib/string.py 中的一个完全不同的函数已弃用,而@BurhanKhalid 答案使用了未弃用的内置字符串方法。他的回答现在和未来都是最正确的,而这仅适用于 2.x。
    • 综上所述,如果您想推广此替代方案,您还应该包括一个警告,说明由于我之前的 cmet 中概述的原因,不推荐这样做。
    • 可怕的是我仍然对此投票。说真的,使用python 3。
    【解决方案5】:
    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 = '
    '.join(list_abc)
    print(string)
    >>> aaa
    >>> bbb
    >>> ccc
    

    【讨论】:

      【解决方案6】:

      我们也可以使用 Python 的 reduce 函数:

      from functools import reduce
      
      sentence = ['this','is','a','sentence']
      out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
      print(out_str)
      

      【讨论】:

      • 太多不必要的复杂性,为什么不使用join
      【解决方案7】:

      我们可以指定我们如何连接字符串。我们可以使用' '代替'-'

      sentence = ['this','is','a','sentence']
      s=(" ".join(sentence))
      print(s)
      

      【讨论】:

        【解决方案8】:

        如果您有一个混合内容列表并想将其字符串化,这是一种方法:

        考虑这个列表:

        >>> aa
        [None, 10, 'hello']
        

        将其转换为字符串:

        >>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
        >>> st = '[' + st + ']'
        >>> st
        '[None, 10, "hello"]'
        

        如果需要,转换回列表:

        >>> ast.literal_eval(st)
        [None, 10, 'hello']
        

        【讨论】:

        • 为什么这么复杂? str(aa)也给"[None, 10, 'hello']"...
        【解决方案9】:

        如果你想在最终结果中生成一串由逗号分隔的字符串,你可以使用这样的东西:

        sentence = ['this','is','a','sentence']
        sentences_strings = "'" + "','".join(sentence) + "'"
        print (sentences_strings) # you will get "'this','is','a','sentence'"
        

        【讨论】:

          【解决方案10】:
          def eggs(someParameter):
              del spam[3]
              someParameter.insert(3, ' and cats.')
          
          
          spam = ['apples', 'bananas', 'tofu', 'cats']
          eggs(spam)
          spam =(','.join(spam))
          print(spam)
          

          【讨论】:

          • 虽然此代码 sn-p 可能是解决方案,但包括解释确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而那些人可能不知道您提出代码建议的原因。
          【解决方案11】:

          如果没有 .join() 方法,您可以使用此方法:

          my_list=["this","is","a","sentence"]
          
          concenated_string=""
          for string in range(len(my_list)):
              if string == len(my_list)-1:
                  concenated_string+=my_list[string]
              else:
                  concenated_string+=f'{my_list[string]}-'
          print([concenated_string])
              >>> ['this-is-a-sentence']
          

          因此,在此示例中,基于范围的 for 循环,当 python 到达列表的最后一个单词时,它不应将“-”添加到您的 concenated_string。如果它不是您字符串的最后一个字,请始终将“-”字符串附加到您的 concenated_string 变量。

          【讨论】:

            猜你喜欢
            • 2016-03-29
            • 1970-01-01
            • 2018-10-15
            • 2017-01-17
            • 1970-01-01
            • 2014-04-19
            • 2021-08-07
            相关资源
            最近更新 更多