【问题标题】:Concatenate python string from list entries [duplicate]从列表条目连接python字符串[重复]
【发布时间】:2015-06-16 11:21:36
【问题描述】:

假设我有一个字符串列表,我想将这些字符串组合成一个由下划线分隔的字符串。我知道我可以使用循环来做到这一点,但是 python 在没有循环的情况下做了很多事情。 python中有什么东西已经有这个功能了吗?例如我有:

string_list = ['Hello', 'there', 'how', 'are', 'you?']

我想制作一个像这样的字符串:

'Hello_there_how_are_you?'

我尝试过的:

mystr = ''    
mystr.join(string_list+'_')

但这给出了一个“TypeError: can only concatenate list (not "str") to list”。我知道这很简单,但不是很明显。

【问题讨论】:

    标签: python string python-2.7


    【解决方案1】:

    您使用加入字符加入列表:

    string_list = ['Hello', 'there', 'how', 'are', 'you?']
    '_'.join(string_list)
    

    演示:

    >>> string_list = ['Hello', 'there', 'how', 'are', 'you?']
    >>> '_'.join(string_list)
    'Hello_there_how_are_you?'
    

    【讨论】:

      【解决方案2】:

      知道了,我用过:

      mystr+'_'.join(string_list)
      'Hello_there_how_are_you?'
      

      我想使用字符串中的连接函数,而不是列表。现在看来很明显了。

      【讨论】:

      • 这里根本不需要使用mystr;它只是一个空字符串。
      猜你喜欢
      • 2018-06-21
      • 2018-08-30
      • 2019-10-23
      • 2020-12-30
      • 2019-01-05
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多