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

0 0