【问题标题】:Concat list and string in Python [duplicate]Python中的Concat列表和字符串[重复]
【发布时间】:2019-01-08 14:04:59
【问题描述】:

我有点不明白Python中添加列表和字符串的原理。

例如,我们有一个列表:

students = ['Ivan', 'Michael', 'Olga']

表达式的结果:

students += 'John'

将是:

['Ivan', 'Michael', 'Olga', 'J', 'o', 'h', 'n']

在这种情况下,字符串 'John' 将作为列表处理,每个符号都将添加到列表 students

但是为什么要处理表达式:

students = students + 'John'

否则会发生吗? 在这种情况下,我们只会得到一个错误。

我一直认为表达式a += ba = a + b 是等价的。 但是为什么在一种情况下字符串被扩展为列表,而在另一种情况下却没有发生并且我们得到一个错误?

【问题讨论】:

标签: python string list concatenation


【解决方案1】:

这是表达式 a += ba = a + b 不会帮助您列出列表。

如果您想在列表中添加一个元素,那么您可以尝试。

students = ['Ivan', 'Michael', 'Olga']
students.append('John')

如果您想加入列表。那你就可以了。

students = ['Ivan', 'Michael', 'Olga']
student = ['John']
students = students + student

或者

 students.extend(student) #This list concatenation method is bit faster.

如果你想深入挖掘。可以参考这个article here

【讨论】:

    猜你喜欢
    • 2012-01-22
    • 2020-10-23
    • 1970-01-01
    • 2013-07-25
    • 2017-01-21
    • 2016-09-19
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    相关资源
    最近更新 更多