Python格式化输出,及使用F-Strings报错原因

格式化输出常用语法

这里我截取了一部分我个人认为常见的格式化输出语法,除了方法四其他的我均使用过(方法四会报错,原因后面会说到), 截取自该链接,大家也可以参考 这篇博客,不过我觉得读那么多没用,不会去用也会忘,先熟练 本文语法完全够用了,二八定律适用于绝大多数场合。
# 方法0, 最原始的方法,类似C语言,不推荐使用
name = "Eric" 
age = 74 
'%s is %s.' % (name, age)

# 方法1, 这里面的0,1为format后面括号里面变量的索引,可以颠倒顺序或者多次使用
In [2]: print('The story of {0}, {1}, and {other}. {0} is the boss.'.format('Bill
   ...: ', 'Manfred',other='Georg'))                                            
The story of Bill, Manfred, and Georg. Bill is the boss.

# 方法2
>>> print('This {food} is {adjective}.'.format(
			food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

# 方法3, 通过使用 '**' 符号将表作为关键字参数传递。且可以用:7d将输出以整型格式化成占位7个字符输出
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
In [5]: print('Jack: {Jack}; Sjoerd: {Sjoerd:7d}; Dcab: {Dcab:d}'.format(**table))                                                                      
Jack: 4098; Sjoerd:    4127; Dcab: 8637678

# 方法4, 注意这种方法一定要在python3.6.2以上的版本上使用,像我的在Python 3.5.2中使用就报错
>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'


综上
format()括号里可以是变量、字符串常量、各常用类型常量、字典的二级指针(C语言里面应该是这么叫吧,在Python不知道怎么叫)等
%(a, b, c)结合c语言里面的%s、%d等占位符使用
方法四叫做F-Strings,要在3.6.2之后的版本使用(也可能是3.7之后的版本),该方法运行速度最快
推荐使用方法一和方法四

正如上所说使用f-string如果版本低了就会报错,error如下:

In [2]: name = "P"                                                              

In [3]: f"myname:{name}"                                                        
  File "<ipython-input-3-990619183aea>", line 1
    f"myname:{name}"
                   ^
SyntaxError: invalid syntax

猜你喜欢

转载自blog.csdn.net/zb0567/article/details/104861382