PEP 0498: Literal String Formatting

2015-08-09 10:43:13 +08:00
 cbsw

PEP 0498

>>> import datetime
>>> name = 'Fred'
>>> age = 50
>>> anniversary = datetime.date(1991, 10, 12)
>>> f'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.'
'My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991.'
>>> f'He said his name is {name!r}.'
"He said his name is 'Fred'."

其它语言里面也有,现在Python终于也要加上了,用起来还是很方便的

3622 次点击
所在节点    程序员
11 条回复
freefcw
2015-08-09 10:47:50 +08:00
这个看着不错,很简洁
janxin
2015-08-09 10:49:42 +08:00
需要3.6,估计要明年才能用上了吧
Septembers
2015-08-09 10:53:46 +08:00
@janxin 3.5才发布没多久
janxin
2015-08-09 10:58:59 +08:00
@Septembers 3.5都还没rc,大概3.6要明年了...
jjx
2015-08-09 14:04:24 +08:00
banxi1988
2015-08-09 15:41:20 +08:00
这语法 ,通过一个Python 特有的前缀 表示法,好像可以少写一个转义字符。
比如 Ruby 是 "#{}" ,Swift 是"\()"
kikyous
2015-08-09 17:54:13 +08:00
ruby和coffee都用n年了
cute
2015-08-10 14:01:41 +08:00
楼上这么说,php只能呵呵了。
zonyitoo
2015-08-10 14:42:13 +08:00
String Interpolation, 脚本语言实现最方便了
Jex
2015-08-11 12:05:14 +08:00
语法有点不一致, Interpolation 直接 Expression 就行了,{name!r} 和 {anniversary:%A, %B %d, %Y} 这种增加了不必要的特殊语法
justahappy
2015-09-20 20:58:13 +08:00
@cute 专科生用的语言 哪来的优越感????????

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/211863

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX