python - 在 Python 中连接列表和字符串

标签 python string list concatenation

<分区>

有点不懂Python中列表和字符串相加的原理。

例如,我们有一个列表:

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

表达式的结果:

学生 += 'John'

将是:

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

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

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

students = students + 'John'

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

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

最佳答案

这是表达式 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

关于python - 在 Python 中连接列表和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51625861/

相关文章:

python - 从 Python 中的统一类获取属性

ruby - 使用#inject 连接数组中的字符串

java - 在android studio中检索if/else子句的字符串

python - 有没有办法从列表创建单列 pandas DataFrame 而不复制列表?

python - 使用 .format 使文本居中的方式正确吗?

python - 如何自定义使用 py.test 生成的 html 报告文件?

python - 从列表中删除重复项,但只保留一些

string - 在不使用 rawValue 的情况下访问枚举中的字符串值

html - 垂直对齐 - 列出 "list-style-image"