python字符串拼接join_Python--字符串拼接方法,持续更新

在Python的实际开发中,很多都需要用到字符串拼接,python中字符串拼接有很多,今天总结一下:

用+符号拼接

用%符号拼接

用join()方法拼接

用format()方法拼接

用string模块中的Template对象

例子:

fruit1 = 'apples'

fruit2 = 'bananas'

fruit3 = 'pears'

要求:

输出字符串’There are apples, bananas, pears on the table’

1. 用+符号拼接

用+拼接字符串如下:

1 str = 'There are'+fruit1+','+fruit2+','+fruit3+' on the table'

该方法效率比较低,不建议使用

2. 用%符号拼接

用%符号拼接方法如下:

1 str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3)

除了用元组的方法,还可以使用字典如下:

1 str = 'There are %(fruit1)s,%(fruit2)s,%(fruit3)s on the table' % {'fruit1':fruit1,'fruit2':fruit2,'fruit3':fruit3}

该方法比较通用

3. 用join()方法拼接

join()`方法拼接如下

1 temp = ['There are ',fruit1,',',fruit2,',',fruit3,' on the table']

2 ''.join(temp)

该方法使用与序列操作

4. 用format()方法拼接

用format()方法拼接如下:

4. 用format()方法拼接

用format()方法拼接如下:

1 str = 'There are {}, {}, {} on the table'

2 str.format(fruit1,fruit2,fruit3)

还可以指定参数对应位置:

1 str = 'There are {2}, {1}, {0} on the table'

2 str.format(fruit1,fruit2,fruit3) #fruit1出现在0的位置

同样,也可以使用字典:

1 str = 'There are {fruit1}, {fruit2}, {fruit3} on the table'

2 str.format(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3)

F-strings

在python3.6.2版本中,PEP 498 提出一种新型字符串格式化机制,被称为“字符串插值”或者更常见的一种称呼是F-strings,F-strings提供了一种明确且方便的方式将python表达式嵌入到字符串中来进行格式化:

>>> s1 = 'Hello' >>> s2 = 'World' >>>f'{s1} {s2}!' 'Hello World!'

在F-strings中我们也可以执行函数:

>>> def power(x): ... return x*x ... >>> x = 5 >>> f'{x} * {x} = {power(x)}' '5 * 5 = 25'

而且F-strings的运行速度很快,比%-string和str.format()这两种格式化方法都快得多。

用string模块中的Template对象

用string模块中的Template对象如下:

1 from string import Template

2 str = Template('There are ${fruit1}, ${fruit2}, ${fruit3} on the table') #此处用的是{},别搞错了哦

3 str.substitute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) #如果缺少参数,或报错如果使用safe_substitute()方法不会

4 str.safe_substitute(fruit1=fruit1,fruit2=fruit2)

5 #输出'There are apples, bananas, ${fruit3} on the table'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值