Python格式化字符串,三种方式你最喜欢哪一种

 

​%  格式

在python中我们可以通过 % 的形式来进行字符串的格式化,例如:

print("I am %s. I am %d years old. I am %.2f meters tall." % ("xiaoming", 18, 1.75))

用 %s 来代替字符串,%d 代替整形,%f 代替浮点数,在填入参数时要一一的对应。如果替换的内容过多就会显得十分乱,字符串中有很多不同替换符,可读性变得很差。

 

 

format()函数

为了解决上面的问题,于是在python2.6中加入了 format() 方法用来格式化字符串。使用方式:

print("I am {}. I am {} years old. I am {} meters tall.".format("xiaoming",18,1.75))

format() 相比与 % 的方式要强大了很多,你不需要考虑数据的类型,并且单个的参数可以重复的使用,参数的顺序也可以不同。让我们看看:

print("I am {a}. hello {b}. I like the {b}".format(b="world", a="xiaoming"))

与此同时,format() 也支持更多的填充方式。除了上面的位置填充,key填充之外,还支持通过列表、字典、类属性和魔法参数的方式来填充。下面举几个例子:

# listIn [1]: arg =["world","python"]     ...:print("hello {arg[0]}. hello {arg[1]}".format(arg=arg))hello world. hello python
# dictIn [2]:  arg ={"key1":"world","key2":"python"}     ...:print("hello {arg[key1]}. hello {arg[key2]}".format(arg=arg))hello world. hello python
# classIn [3]:classArgs():     ...:     key1 ="world"     ...:     key2 ="python"     ...:      ...:print("hello {arg.key1}. hello {arg.key2}".format(arg=Args)hello world. hello python
# magicIn [18]: args =[",","."]     ...: kwargs ={"w":"world","p":"python"}     ...:print("hello {w}{} hello {p}{}".format(*args,**kwargs))  hello world, hello python.

不仅填充的方式多样,format() 还支持多种填充格式的转换和对齐,我就直接用实例来说明,代码如下:

# {:.2f} 保留小数点后两位小数In [1]: print("{:.2f}".format(3.14159265358))    >>> 3.14# {+:.2f} 带符号保留小数点后两位小数   In [2]: print("{:+.2f}".format(-3.14159265358))>>> -3.14# {:,} 千位分割符      In [3]: print("{:,}".format(10000000000))            >>> 10,000,000,000# {:.3%} 百分比格式,保留三位小数   In [4]: print("{:.3%}".format(3.14159265358))                      >>> 314.159%# {:.2e} 指数记法,保留两位小数  In [5]: print("{:.2e}".format(3.14159265358))   >>> 3.14e+00# {:b} 二进制转换In [6]: print("{:b}".format(16))          >>> 10000# {:d} 十进制转换In [7]: print("{:d}".format(16))          >>> 16# {:o} 八进制转换In [8]: print("{:o}".format(16))        >>> 20# {:x} 十六进制转换In [9]: print("{:x}".format(16))                                                                                                            >>> 10# {:x>4} x填充左边,总长度4(不设置填充字符,默认空格)In [10]: print("{:x>4}".format(10))                                                                                                          >>> xx10# {:x<4} x填充右边,总长度4In [11]: print("{:x<4}".format(10))                                                                                                          >>> 10xx# {:x^4} x填充两侧,总长度4(优先左填充)In [12]: print("{:x^4}".format(10))                                                                                                          >>> x10x                                     

 

 

'f{}'     f-字符串

同样如果替换的内容过多,format() 有时就会看起来十分的臃肿。于是在python3.6的更新中加入了 f-string ,格式如下:

name = "xiaoming"age = 18print(f"His name is {name}, he's {age} years old.")

是不是看起来更加简洁了,而且使用功能上和 format() 一样,并且支持数学运算和对象操作:

In [1]: person = {"name":"xiaoming", "age":18}     ...: print(f"I am {person['name']}. I am {person['age']+1} years old. {len(person)} sentences")I am xiaoming. I am 19 years old. 2 sentences

如今在python3.8的更新中进一步提升了 f-string,支持 = 用于自动记录表达式和调试文档,实例如下:

In [1]: from datetime import date                                                                                                           In [2]: user = 'eric_idle'    ...: member_since = date(1975, 7, 31)    ...: print(f'{user=} {member_since=}')                                                                                                      user='eric_idle' member_since=datetime.date(1975, 7, 31)

现在官方更加推荐使用 f-string,不过看到这里你喜欢哪种方式呢?

 

参考资料

[1]Python 官方文档: https://docs.python.org/zh-cn/3/library/functions.html?highlight=format#format

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值