Python学习笔记-- 字符串和数字的连接

Python学习笔记– 字符串和数字的连接

>>> s = 'abc'
>>> print s + 1

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    print s + 1
TypeError: 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,s
1 abc
>>> print 1,s
1 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' + 1

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    print 'abc' + 1
TypeError: cannot concatenate 'str' and 'int' objects
>>> 

“+”运算符有连接字符串的作用(在连接两个字符串是重载为字符串连接符),但是在连接字符串和数字时,会被认为是运算符加号,而在加法运算中,出现了类型不一致,所以报错。


引用博文
[1]:python中%r和%s的区别
http://blog.csdn.net/wusuopubupt/article/details/23678291

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值