多行字符串拼接使用小括号python2
s = ('select *' 'from atable' 'where id=888') print s, type(s) #输出 select * from atable where id=888 <type 'str'>
python3
s = ('select *' 'from atable' 'where id=888') print (s), type(s) #输出 select * from atable where id=888 <type 'str'>
python遇到未闭合的小括号,自动将多行拼接为一行,相比三个引号和换行符,这种方式不会把换行符、前导空格当作字符。
下面是一些补充
python3 拼接字符串的7种方法
1、直接通过(+)操作符拼接
> 'Hello' + ' ' + 'World' + '!'
'Hello World!'
使用这种方式进行字符串连接的操作效率低下,因为python中使用 + 拼接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当拼接字符串较多时自然会影响效率。
2、通过str.join()方法拼接
> strlist = ['Hello', ' ', 'World', '!']
> ''.join(strlist)
'Hello World!'
这种方式一般常使用在将集合转化为字符串,''.join()其中''可以是空字符,也可以是任意其他字符,当是任意其他字符时,集合中字符串会被该字符隔开。
3、通过str.format()方法拼接
> '{} {}!'.format('Hello', 'World')
'Hello World!'
通过这种方式拼接字符串需要注意的是字符串中{}的数量要和format方法参数数量一致,否则会报错。
4、通过(%)操作符拼接
> '%s %s!' % ('Hello', 'World')
'Hello World!'
这种方式与str.format()使用方式基本一致。
5、通过()多行拼接
> (
... 'Hello'
... ' '
... 'World'
... '!'
... )
'Hello World!'
python遇到未闭合的小括号,自动将多行拼接为一行。
6、通过string模块中的Template对象拼接
> from string import Template
> s = Template('${s1} ${s2}!')
> s.safe_substitute(s1='Hello',s2='World')
'Hello World!'
Template的实现方式是首先通过Template初始化一个字符串。这些字符串中包含了一个个key。通过调用substitute或safe_subsititute,将key值与方法中传递过来的参数对应上,从而实现在指定的位置导入字符串。这种方式的好处是不需要担心参数不一致引发异常,如:
> from string import Template
> s = Template('${s1} ${s2} ${s3}!')
> s.safe_substitute(s1='Hello',s2='World')
'Hello World ${s3}!'
7、通过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()这两种格式化方法都快得多。
以上这篇python多行字符串拼接使用小括号的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 杨千嬅.2002-万紫千红演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郭采洁.2015-Begin.Again爱造飞鸡【华纳】【FLAC分轨】
- 许志安.2011-ON.AND.ON【东亚】【WAV+CUE】
- 潘秀琼.1994-木兰从军【名将】【WAV+CUE】
- 纯音入心系列纯音乐《古筝系列-当流行乐遇到古筝》1CD[MP3][1.9GB]
- 纯音入心系列纯音乐《精选古筝名曲100首》1CD[MP3][388.7MB]
- 纯音入心系列纯音乐《天籁古筝》1CD[MP3][331MB]
- 男女对唱典藏天碟《发烧对唱·那个季节里的歌DSD》10CD[WAV]
- 群星2010-歌林精选辑[歌林][WAV+CUE]
- TrioZimbalist-PianoTriosofWeinberg,Auerbach,Dvorak(2024)[24-44,1]wav
- 群星.1992-滚石第一流台湾歌·12王牌大车拼【滚石】【WAV+CUE】
- 林子祥.1984-创作歌集【华纳】【WAV+CUE】
- 周汤豪.2010-周汤豪【华纳】【FLAC分轨】
- Mozart-TheStringQuintets-AmadeusQuartet,CecilAronowitz(2017)[24-44,1][WAV+CUE]
- JamesWilliamsDennisIrwin-Focus(2024,Red)[24-48]FLAC