首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Python3.6中格式化的字符串文本是什么?

在Python3.6中格式化的字符串文本是什么?
EN

Stack Overflow用户
提问于 2016-08-22 14:10:50
回答 3查看 5.4K关注 0票数 19

Python3.6的一个特性是格式化字符串。

This SO question(python-3.6中前缀为'f‘的字符串)询问格式化字符串文字的内部结构,但我不明白格式化字符串文本的确切用例。在什么情况下我应该使用这个特性?明示不比内隐好吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-08-22 14:26:49

简单胜于复杂。

所以这里我们已经格式化了字符串。它使字符串格式化变得简单,同时保持代码的显式(与其他字符串格式机制相比较)。

代码语言:javascript
运行
复制
title = 'Mr.'
name = 'Tom'
count = 3

# This is explicit but complex
print('Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count))

# This is simple but implicit
print('Hello %s %s! You have %d messages.' % (title, name, count))

# This is both explicit and simple. PERFECT!
print(f'Hello {title} {name}! You have {count} messages.')

它的设计是为了取代str.format用于简单的字符串格式设置。

票数 35
EN

Stack Overflow用户

发布于 2018-07-02 08:48:43

Pro: F-文字有更好的性能。(见下文)

Con: F-文字是一个新的3.6功能.

代码语言:javascript
运行
复制
In [1]: title = 'Mr.'
   ...: name = 'Tom'
   ...: count = 3
   ...: 
   ...: 

In [2]: %timeit 'Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count)
330 ns ± 1.08 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [3]: %timeit 'Hello %s %s! You have %d messages.'%(title, name, count)
417 ns ± 1.76 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %timeit f'Hello {title} {name}! You have {count} messages.'
13 ns ± 0.0163 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
票数 3
EN

Stack Overflow用户

发布于 2018-07-19 16:49:41

比较所有4种字符串格式的性能

title = 'Mr.' name = 'Tom' count = 3

%timeit 'Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count)

每环198 ns±7.88ns(平均±std )。dev.7次运行中,每一次循环1000000次)

%timeit 'Hello {} {}! You have {} messages.'.format(title, name, count)

每环329 ns±7.04 ns (平均±std )。dev.7次运行中,每一次循环1000000次)

%timeit 'Hello %s %s! You have %d messages.'%(title, name, count)

每环264 ns±6.95ns(平均±std )。dev.7次运行中,每一次循环1000000次)

%timeit f'Hello {title} {name}! You have {count} messages.'

每环12.1ns±0.0936 ns (平均±std )。dev.7次运行中,每一次循环100000000次)

因此,字符串格式化的最新方法来自python3.6,也是最快的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39081766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档