不太清楚%s在Python中的意义,帮助吗?

2024-06-16 12:32:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从一本书中学习Python,我不明白使用%s在列表、字符串、字典等中定位特定项的意义何在

例如:

names = ["jones", "cohen", "smith", "griffin"]

print(names[1])
print("%s" % names[1])

两个命令都打印“cohen”,使用%s有什么意义?在


Tags: 字符串定位命令列表字典names意义smith
3条回答

%s用于构造字符串。在

在python中,与许多其他语言一样,字符串是不可变的。因此,如果串联了许多字符串,那么每个字符串都会被创建并存储在内存中,等待被垃圾回收。在

因此,%s的要点是,如果必须连接许多不同的字符串,则只需构造一次字符串,从而节省不必要的内存开销。在

它也可以说是比+更方便的语法,并且可以在需要的地方中断字符串。在

python中的%s是用于格式化的。在

a = 1.23
print "The value is %0.5f" %(a) # prints 1.23000

想让你更容易创作出更复杂的创意

print("The name is %s!" % names[1])

而不是

^{pr2}$

但是,由于您刚刚开始使用Python,您应该立即开始学习new string formatting syntax

print("The name is {}!".format(names[1])

当然,这个例子不能展示字符串格式化方法的真正威力。你可以做更多的事情,例如(摘自上面链接的文档):

>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

等等。。。在

相关问题 更多 >