stack=s+stack#TypeError: can only concatenate str (not “list“) to str

PYTHON的神奇操作

复制代码
stack=['1','2']
s="ddd"
# stack=s+stack#TypeError: can only concatenate str (not "list") to str
stack+=s
print(stack)#['1', '2', 'd', 'd', 'd']
复制代码
stack=['1','2']
s="ddd"
stack=s+stack  # 这里会报错,因为不能直接将字符串和列表相加
stack+=s  # 这行不会报错,会将字符串 s 追加到列表 stack 中

在 Python 中,不能直接将字符串和列表进行相加操作,这会引发 TypeError 错误。但使用 += 操作符时,如果操作对象是列表,它会尝试将右侧的可迭代对象(如字符串)的元素逐个追加到列表中。

相关推荐
曲幽8 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
装不满的克莱因瓶8 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..8 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
金銀銅鐵9 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf9 小时前
Python 模块与包的导入导出
前端·后端·python
ice8130331819 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
copyer_xyf9 小时前
Python venv 虚拟环境
前端·后端·python
林爷万福10 小时前
GitHub 开源光谱数据处理项目推荐
python·光纤光谱仪
copyer_xyf11 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python
Full Stack Developme11 小时前
Spring Bean 依赖注入
python·spring·log4j