首页 > 编程语言 > 详细

Python拼接字符串的7种方法

时间:2018-08-18 14:12:22      阅读:142      评论:0      收藏:0      [点我收藏+]

1、直接通过+操作:

s = ‘Python‘+‘,‘+‘你好‘+‘!‘
print(s)

打印结果:

Python,你好!

 

2、通过join()方法拼接:

将列表转换成字符串

strlist=[‘Python‘, ‘,‘, ‘你好‘, ‘!‘]
print(‘‘.join(strlist))

打印结果:

Python,你好!

 

3、通过format()方法拼接:

字符串中{}的数量要与format()方法中的参数数量一致

s = ‘{},{}!‘.format(‘Python‘, ‘你好‘)
print(s)

打印结果:

Python,你好!

 

4、通过%拼接:

s = ‘%s,%s!‘ % (‘Python‘, ‘你好‘)
print(s)

打印结果:

Python,你好!

 

5、通过()多行拼接:

当Python遇到未闭合的小括号,会自动将多行拼接成一行

s = (
‘Python‘
‘,‘
‘你好‘
‘!‘
)
print(s)

打印结果:

Python,你好!

 

6、通过string模块中的Template对象拼接:

from string import Template


s = Template(‘${s1},${s2}!‘)
# Template的实现方式是首先通过Template初始化一个字符串
# 这些字符串中包含了一个个key
print(s.safe_substitute(s1=‘Python‘, s2=‘你好‘))
# 通过调用substitute或safe_subsititute
# 将key值与方法中传递过来的参数对应上
# 从而实现在指定的位置导入字符串

打印结果:

Python,你好!

 

7、通过F-strings(字符串插值)拼接:

s1 = ‘Python‘
s2 = ‘你好‘
print(f‘{s1},{s2}!‘)

打印结果:

Python,你好!

Python拼接字符串的7种方法

原文:https://www.cnblogs.com/yjlch1016/p/9497123.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!