【问题标题】:How do you concatenate with a list?你如何与列表连接?
【发布时间】:2022-01-12 03:54:40
【问题描述】:

我对 python 比较陌生,我正在尝试与列表连接。这是我最好的尝试,但显然它不起作用。有人知道这样做的方法吗?谢谢

present = ["Jake", "Jimmy", "Karen"]
print("The people present are " + present)

【问题讨论】:

  • 你想要发生什么?你想打印出人的名字吗?逗号分隔?您真的想要打印整个列表、括号和所有内容吗?
  • print("The people present are " + str(present)) ?
  • 感谢atline,这就是我想要做的一切:D
  • 您也可以将多个参数传递给print,例如print("The people present are", present)print 会自动将每个单独的参数转换为字符串。

标签: python concatenation


【解决方案1】:

您需要先将列表转换为字符串,然后才能使用+ 运算符进行字符串连接。您可以使用str.join() 方法来完成此操作。

present = ["Jake", "Jimmy", "Karen"]
print("The people present are " + ", ".join(present))

这将为列表中的每个项目创建一个字符串,并使用字符串', ' 作为每个元素之间的分隔符。

在此处查看 w3 学校示例https://www.w3schools.com/python/ref_string_join.asp

或者官方python文档https://docs.python.org/3/library/stdtypes.html#str.join

【讨论】:

    【解决方案2】:

    你可能想要str.join

    >>> some_list = ['Jack', 'Jill', 'Hill']
    >>> print("The story centrally features the characters: " + ", ".join(some_list))
    The story centrally features the characters: Jack, Jill, Hill
    

    【讨论】:

      猜你喜欢
      • 2018-11-07
      • 2019-06-06
      • 2014-08-05
      • 2020-11-17
      • 2010-09-21
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 2013-07-02
      相关资源
      最近更新 更多