简单总结Python中几种字符串连接的方法

# 本文所述内容为python2.7下的情况,未在python3.x上进行测试,因为太懒得意 #

学习Python有了一段时间,今天突然想起字符串连接的东西,想总结一下。

总的来说字符串连接的方式总共有一下几种:

第一种:

第一种也是最为常见易于理解的一种,直接使用 "+" 进行操作,例如:

 

>>> print "hello" + "world"
helloworld

 

 

 

第二种:

使用占位符%s,例如:

 

>>> s = "apple"
>>> print "I want to eat an %s" % s
I want to eat an apple

 

当然也可以一个字符串中出现多个占位符

 

>>> color1 = "black"
>>> color2 = "red"
>>> print "I have a %s pen and a %s pen." % (color1, color2)
I have a black pen and a red pen.

 

 

第三种:

使用format函数,例如:

# 还是使用上面的例子

 

>>> print "I have a {} pen and a {} pen.".format(color1, color2)
I have a black pen and a red pen.

当参数过多时,也可以通过指定名字的方式进行操作:

 

 

>>> print "I have a {a} pen and a {b} pen.".format(a=color1, b=color2)
I have a black pen and a red pen.

 

 

第四种:

 

>>> print "I have a %(a)s pen and a %(b)s pen." % {'a': color1, 'b': color2}
I have a black pen and a red pen.

 


以上方法介绍的都比较简单,仅供参考~

 

 

 

 

 

 


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值