Python字符串插入整数变量报错,如何实现变量运算后嵌入?
解决Python字符串拼接中的TypeError问题
嘿,作为Python新手遇到这个问题太正常了,我来帮你搞定!
你碰到的TypeError: coercing to Unicode: need string or buffer, int found错误,根源是在拼接字符串时直接混用了整数类型的值。Python里字符串和整数不能直接拼接,必须先把整数转换成字符串类型才行。
你的需求是把c=5运算成7(也就是c+2)后嵌入到第二个方括号里,这里给你几种简单靠谱的实现方式:
方法1:用str()转换整数为字符串
先算出目标数值,再把它转成字符串后拼接,逻辑清晰不容易错:
c = 5 target_value = c + 2 # 得到运算后的7 cmds.pointPosition(geo[0] + ".cv[0][" + str(target_value) + "]", w=True)
方法2:用f-string(推荐,Python3.6+可用)
f-string是Python里最简洁直观的字符串格式化方式,直接在字符串里嵌入变量,自动帮你处理类型转换,写起来超清爽:
c = 5 target_value = c + 2 cmds.pointPosition(f"{geo[0]}.cv[0][{target_value}]", w=True)
方法3:用str.format()方法
如果你的Python版本比较老(低于3.6),可以用这种兼容性拉满的方式:
c = 5 target_value = c + 2 cmds.pointPosition("{}.cv[0][{}]".format(geo[0], target_value), w=True)
这几种方法都能完美解决你的问题,个人最推荐f-string,可读性高还不容易写漏符号~
内容的提问来源于stack exchange,提问作者Vlad
相关产品推荐
相关产品推荐

