简单总结Python中几种字符串连接的方法
2015-12-08 15:24
841 查看
# 本文所述内容为python2.7下的情况,未在python3.x上进行测试,因为太懒
#
学习Python有了一段时间,今天突然想起字符串连接的东西,想总结一下。
总的来说字符串连接的方式总共有一下几种:
第一种:
第一种也是最为常见易于理解的一种,直接使用 "+" 进行操作,例如:
第二种:
使用占位符%s,例如:
当然也可以一个字符串中出现多个占位符
第三种:
使用format函数,例如:
# 还是使用上面的例子
第四种:
以上方法介绍的都比较简单,仅供参考~
#
学习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.
以上方法介绍的都比较简单,仅供参考~
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法