Zac*_*iro 3 python syntax string-formatting
我正在从一本书中学习Python,我无法弄清楚使用%s来列出列表,字符串,字典等中的特定项目是什么意思.
例如:
names = ["jones", "cohen", "smith", "griffin"]
print(names[1])
print("%s" % names[1])
Run Code Online (Sandbox Code Playgroud)
这两个命令都打印出"cohen",使用%s的重点是什么?
Tim*_*ker 14
这个想法是让你轻松创建更复杂的输出
print("The name is %s!" % names[1])
Run Code Online (Sandbox Code Playgroud)
代替
print("The name is " + names[1] + "!")
Run Code Online (Sandbox Code Playgroud)
但是,当您刚刚开始使用Python时,您应该立即开始学习新的字符串格式化语法:
print("The name is {}!".format(names[1])
Run Code Online (Sandbox Code Playgroud)
当然,这个例子无法显示字符串格式化方法的真正威力.例如,您可以使用这些内容进行更多操作(取自上面链接的文档):
>>> '{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'
Run Code Online (Sandbox Code Playgroud)
等等...