python3.6

您所在的位置:网站首页 python中str的含义 python3.6

python3.6

2023-11-28 03:33| 来源: 网络整理| 查看: 265

Option #2: str.format()

这种更新的工作方式是在Python 2.6中引入的。您可以查看Python文档以获取更多信息。

怎样使用Use str.format()

str.format()是对%-formatting的改进。它使用正常的函数调用语法,并且可以通过对要转换为字符串的对象的__format __()方法进行扩展。

使用str.format(),替换字段用大括号标记:

 

1

 

"Hello, {}. You are {}.".format(name, age)

'Hello, Eric. You are 74.'

您可以通过引用其索引来以任何顺序引用变量:

 

1

 

"Hello, {1}. You are {0}-{0}.".format(age, name)

'Hello, Eric. You are 74-74.'

但是,如果插入变量名称,则会获得额外的能够传递对象的权限,然后在大括号之间引用参数和方法:

 

1

2

 

person = {'name': 'Eric', 'age': 74}

"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])

'Hello, Eric. You are 74.'

你也可以使用**来用字典来完成这个巧妙的技巧:

 

1

 

"Hello, {name}. You are {age}.".format(**person)

'Hello, Eric. You are 74.'

与f-string相比,str.format()绝对是一个升级版本,但它并非总是好的。

为什么 str.format() 并不好

使用str.format()的代码比使用%-formatting的代码更易读,但当处理多个参数和更长的字符串时,str.format()仍然可能非常冗长。看看这个:

 

 

 

1

2

3

4

5

6

7

8

9

 

 

 

first_name = "Eric"

last_name = "Idle"

age = 74

profession = "comedian"

affiliation = "Monty Python"

print(("Hello, {first_name} {last_name}. You are {age}. " +

 

"You are a {profession}. You were a member of {affiliation}.")

 

.format(first_name=first_name, last_name=last_name, age=age,

profession=profession, affiliation=affiliation))

Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.

如果你有想要传递给字典中的.format()的变量,那么你可以用.format(** some_dict)解压缩它,并通过字符串中的键引用这些值,但是必须有更好的的方法

f-Strings:一种改进Python格式字符串的新方法

好消息是,F字符串在这里可以节省很多的时间。他们确实使格式化更容易。他们自Python 3.6开始加入标准库。您可以在PEP 498中阅读所有内容。

也称为“格式化字符串文字”,F字符串是开头有一个f的字符串文字,以及包含表达式的大括号将被其值替换。表达式在运行时进行渲染,然后使用__format__协议进行格式化。与往常一样,Python文档是您想要了解更多信息的最佳读物。

以下是f-strings可以让你的生活更轻松的一些方法。

简单例子

语法与str.format()使用的语法类似,但较少细节啰嗦。看看这是多么容易可读:

 

1

2

3

 

name = "Eric"

age = 74

f"Hello, {name}. You are {age}."

'Hello, Eric. You are 74.'

使用大写字母F也是有效的:

 

1

 

F"Hello, {name}. You are {age}."

'Hello, Eric. You are 74.'

你喜欢F格式化字符串吗?我希望在本文的最后,你会回答>>> F"{Yes!}"。

转载:

http://www.cnblogs.com/c-x-a/p/9333826.html



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3