Python学习笔记-- 字符串和数字的连接
来源:互联网 发布:哪款vpn软件好 编辑:程序博客网 时间:2024/05/24 01:46
Python学习笔记– 字符串和数字的连接
>>> s = 'abc'>>> print s + 1Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> print s + 1TypeError: cannot concatenate 'str' and 'int' objects
上面运算中提到出现了类型错误,这里不难看出是类型转换的问题对于类似问题,有以下几种解决办法:
- 通过str构造函数来实现
>>> s = 'abc'>>> print s + str(1)abc1
通过help(str),我们可以获得以下帮助信息(python2.7.9)
str(object=”) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
我们不难看出,传入数字1到str()中,会返回1的字符串表现形式,即将数字1转换为string类型。
- 通过字符串的格式化
>>> s = 'abc'>>> print "%s%s"%(s,1)abc1>>>
这里是因为%s就是通过str()来处理对象的(详见:python中%r和%s的区别)
- 通过print来实现
>>> s = 'abc'>>> x = 1>>> print x,s1 abc>>> print 1,s1 abc
在print的帮助信息中有如下信息:
“print” evaluates each expression in turn and writes the resulting
object to standard output (see below). If an object is not a string,
it is first converted to a string using the rules for string
conversions.
意思就是说,当打印的对象不是string,会先进行向string类型的转换
>>> print 'abc' + 1Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> print 'abc' + 1TypeError: cannot concatenate 'str' and 'int' objects>>>
“+”运算符有连接字符串的作用(在连接两个字符串是重载为字符串连接符),但是在连接字符串和数字时,会被认为是运算符加号,而在加法运算中,出现了类型不一致,所以报错。
引用博文
[1]:python中%r和%s的区别
http://blog.csdn.net/wusuopubupt/article/details/23678291
- Python学习笔记-- 字符串和数字的连接
- Python学习笔记五:数字和字符串
- Python学习第一篇之python 连接字符串和数字
- Python学习笔记-数字&字符串
- Python学习笔记(一)数字和字符串
- Python学习笔记(2)- 字符串和数字
- Python学习笔记——字符串连接
- 学习笔记----字符串的连接
- Python tutorial: python中文快速学习笔记 - 数字与字符串
- Python学习笔记(六)数字与字符串…
- Python学习笔记(数字)
- Python学习笔记之一:Python的字符串
- python学习笔记-字符串和编码
- Python学习笔记 - 字符串和编码
- Python学习笔记—字符串和编码
- 【Python学习笔记】字符串和编码
- 【Python学习笔记】-字符串和字典
- 【python】list的字符串连接和分割
- C++课程设计
- 贝叶斯分类学习笔记
- 关于混合(Blend)和浮点纹理的一件小事
- 黑马程序员——OC三大特性-7:多态
- IIS HTTP 错误 403.14 - Forbidden Web 服务器被配置为不列出此目录的内容
- Python学习笔记-- 字符串和数字的连接
- Java就业指导
- jQuery EasyUI 为Combo,Combobox添加清除值功能
- IOS lib(.a)库冲突解决办法
- 跑Tracking-Learning-Detection (TLD)是遇到的问题及解决方法
- tomcat项目部署
- C++ Vector的使用
- sql操作总结
- 14:Longest Common Prefix【字符串】