【问题标题】:Python: Combining string and listsPython:组合字符串和列表
【发布时间】:2012-01-07 10:53:56
【问题描述】:

我有一个计数器列表

counters = ['76195087', '963301809', '830123644', '60989448', '0', '0', '76195087', '4006066839', '390361581', '101817210', '0', '0']

我想使用其中一些计数器创建一个字符串....

cmd = 'my_command' + counters[0:1]

但我发现我无法连接字符串和列表。

最后我必须有一个如下所示的字符串:

my_command 76195087

如何将这些数字从它们的列表中取出并让它们表现得像字符串?

【问题讨论】:

    标签: python string list concatenation


    【解决方案1】:

    如果你只想附加一个计数器,你可以使用

    "my_command " + counters[0]
    

    "%s %s" % (command, counters[0])
    

    其中command 是一个包含命令字符串的变量。如果您想添加多个计数器,' '.join() 是您的朋友:

    >>> ' '.join([command] + counters[:3])
    'my_command 76195087 963301809 830123644'
    

    【讨论】:

    • 双引号重要吗?当我使用单引号时,我收到以下消息:TypeError: cannot concatenate 'str' and 'list' objects
    • 也...我需要在命令中使用几个计数器作为参数。如何引入多个柜台? + 计数器 [0] + 计数器 [3] 等?
    • @TheWellington 双引号和单引号一样,I doubt you are using the exact code above
    【解决方案2】:

    您必须访问列表的 元素,而不是列表的 子列表,如下所示:

    cmd = 'my_command' + counters[0]
    

    因为我猜你有兴趣在某个时候使用所有计数器,所以使用一个变量来存储你当前使用的索引,并在你认为合适的地方增加它(可能在循环内)

    idx = 0
    cmd1 = 'my_command' + counters[idx]
    idx += 1
    cmd2 = 'my_command' + counters[idx]
    

    当然,小心不要将索引变量增加到超出列表的大小。

    【讨论】:

      【解决方案3】:

      如果您只想要列表中的单个元素,只需索引该元素即可:

      cmd = 'my_command ' + counters[0]
      

      如果要连接多个元素,请使用字符串的 'join()' 方法:

      cmd = 'my_command ' + " ".join(counters[0:2]) # add spaces between elements
      

      【讨论】:

        【解决方案4】:

        您可以使用join 列表中的join 字符串:

        cmd = 'my_command' + ''.join(counters[:1])
        

        但你不应该首先构造这样的命令并将其提供给os.popenos.system。相反,请使用 subprocess 模块,它处理内部结构(并转义有问题的值):

        import subprocess
        # You may want to set some options in the following line ...
        p = subprocess.Popen(['my_command'] + counters[:1])
        p.communicate()
        

        【讨论】:

          猜你喜欢
          • 2020-01-16
          • 1970-01-01
          • 1970-01-01
          • 2018-02-19
          • 1970-01-01
          • 1970-01-01
          • 2021-12-18
          • 2020-09-30
          • 2021-04-07
          相关资源
          最近更新 更多