Python 3.6中的格式化字符串文字是什么? [英] What are formatted string literals in Python 3.6?

查看:100
本文介绍了Python 3.6中的格式化字符串文字是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.6的功能之一是格式化字符串.

One of the features of Python 3.6 are formatted strings.

此问题(带'f'的字符串python-3.6中的prefix)询问格式化字符串文字的内部信息,但我不了解格式化字符串文字的确切用例.在哪些情况下应该使用此功能?显性比隐性好吗?

This SO question(String with 'f' prefix in python-3.6) is asking about the internals of formatted string literals, but I don't understand the exact use case of formatted string literals. In which situations should I use this feature? Isn't explicit better than implicit?

推荐答案

简单胜于复杂.

Simple is better than complex.

所以这里我们格式化了字符串.它使字符串格式化更加简单,同时保持代码明确(与其他字符串格式化机制相比).

So here we have formatted string. It gives the simplicity to the string formatting, while keeping the code explicit (comprared to other string formatting mechanisms).

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以便进行简单的字符串格式化.

It is designed to replace str.format for simple string formatting.

这篇关于Python 3.6中的格式化字符串文字是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆