lee-romantic 's Blog
Everything is OK!
Toggle navigation
lee-romantic 's Blog
主页
About Me
归档
标签
Python字符串拼接
2019-06-25 13:38:42
248
0
0
lee-romantic
python经常要进行字符串的拼接操作,下面是一些方法: ###(1)用+符号拼接 ``` str = 'There are'+fruit1+','+fruit2+','+fruit3+' on the table' ``` ###(2)用%符号拼接 ``` str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3) ``` 或者: ``` str = 'There are %(fruit1)s,%(fruit2)s,%(fruit3)s on the table' % {'fruit1':fruit1,'fruit2':fruit2,'fruit3':fruit3} ``` ###(3)用join()方法拼接 ``` temp = ['There are ',fruit1,',',fruit2,',',fruit3,' on the table'] 2 ''.join(temp) ``` 注意,与`os.path.join()`不是一回事,`os.path.join()`是拼接时会自动加上`/`的,因为是路径的拼接 ###(4)用format()方法拼接 ``` >>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world' ``` ``` # 通过字典设置参数 site = {"name": "菜鸟教程", "url": "www.runoob.com"} print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['菜鸟教程', 'www.runoob.com'] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的 ``` 格式化数字: ``` >>> print("{:.2f}".format(3.1415926)); 3.14 ``` format格式化输出更详细参考菜鸟教程: https://www.runoob.com/python/att-string-format.html ###(5)用string模块中的Template对象 参考链接: https://www.cnblogs.com/jamsent/p/7183905.html
上一篇:
ubuntu下的screen多重视窗管理程序
下一篇:
linux可执行文件没有扩展名
0
赞
248 人读过
新浪微博
微信
腾讯微博
QQ空间
人人网
提交评论
立即登录
, 发表评论.
没有帐号?
立即注册
0
条评论
More...
文档导航
没有帐号? 立即注册