网络编程
位置:首页>> 网络编程>> Python编程>> 如何在python字符串中输入纯粹的{}

如何在python字符串中输入纯粹的{}

作者:丁壮  发布时间:2023-09-21 22:56:41 

标签:python,字符串,{},连接

python的format函数通过{}来格式化字符串


>>> a='{0}'.format(123)
>>> a
'123'

如果需要在文本中包含{}字符,这样使用就会报错:


>>> a='{123} {0}'.format('123')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

需要通过{{}},也就是double的{}来进行转义


>>> a='{{123}} {0}'.format('123')
>>> a
'{123} 123'

参考链接:

    https://docs.python.org/3/library/string.html#formatstrings

下面看下python字符串连接的三种方法

python字符串连接的方法,一般有以下三种:方法1:直接通过加号(+)操作符连接website=& 39;python& 39;+& 39;tab& 39;+& 39; com& 39;方法2

python字符串连接的方法,一般有以下三种:

方法1:直接通过加号(+)操作符连接


website = 'python' + 'tab' + '.com'

方法2:join方法


listStr = ['python', 'tab', '.com']
website = ''.join(listStr)

方法3:替换


website = '%s%s%s' % ('python', 'tab', '.com')

下面再来说一下三种方法的不同

方法1,使用简单直接,但是网上不少人说这种方法效率低

之所以说python 中使用 + 进行字符串连接的操作效率低下,是因为python中字符串是不可变的类型,使用 + 连接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当连续相加的字符串很多时(a+b+c+d+e+f+...) ,效率低下就是必然的了

方法2,使用略复杂,但对多个字符进行连接时效率高,只会有一次内存的申请。而且如果是对list的字符进行连接的时候,这种方法必须是首选

方法3:字符串格式化,这种方法非常常用,本人也推荐使用该方法

总结

以上所述是小编给大家介绍的如何在python字符串中输入纯粹的{}网站的支持!

来源:https://www.cnblogs.com/flashBoxer/archive/2018/08/22/9518710.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com