代码之家  ›  专栏  ›  技术社区  ›  devnull

迭代api调用的列表和格式[重复]

  •  -3
  • devnull  · 技术社区  · 5 年前

    假设我有一个字符串列表,我想把它们拼凑成一个用下划线分隔的字符串。我知道我可以使用循环来实现这一点,但python在没有循环的情况下做了很多事情。python中是否已经有了这个功能?例如,我有:

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

    我想做一个字符串,比如:

    'Hello_there_how_are_you?'
    

    我所尝试的:

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

    但这给出了一个“TypeError:只能将列表(而不是“str”)连接到列表”。我知道这很简单,但并不明显。

    0 回复  |  直到 10 年前
        1
  •  35
  •   Martijn Pieters    10 年前

    你使用 加入角色 加入列表:

    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
  •  1
  •   veda905    10 年前

    我用过了:

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

    我想从字符串而不是列表中使用join函数。现在看来很明显。