python - 避免在字符串中指定相同值的最pythonic方法是什么

message = "hello %s , how are you %s, welcome %s"%("john","john","john")

避免指定“john”3 次而是指定一个短语的最 Pythonic 方式是什么。

最佳答案

我不会使用 % 格式,.format 有很多优点。此外,最初计划删除 % 格式并用 .format 替换它,尽管显然这实际上并没有发生。

A new system for built-in string formatting operations replaces the % string formatting operator. (However, the % operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time.) Read PEP 3101 for the full scoop.

>>> "hello {name}, how are you {name}, welcome {name}".format(name='john')
'hello john, how are you john, welcome john'

我更喜欢第一种方式,因为它是明确的,但这就是为什么 .format 优于 % 格式

>>> "hello {0}, how are you {0}, welcome {0}".format('john')
'hello john, how are you john, welcome john'

https://stackoverflow.com/questions/11921649/

相关文章:

string - 如何在 Haskell 中填充整数的字符串表示形式?

java - 格式字符串变为 xxx1、xx10 或 1###、10## 等

c# - 为什么只有一个语句的方法需要大括号?

python - 在 Python 中使用 LaTeX 表示法格式化数字

latex - 如何在 LaTeX 中的空格后设置制表位?

wpf - 使用小数分隔符格式化 XAML 中的值?

formatting - 在 Redmine wiki 页面中插入特殊字符

php - 正则表达式 - 去除非数字并删除美分(如果有)

c# - 使用 .NET 格式化大数

iphone - 时间跨度的智能格式化