第五章 python3字符串

 

在开始之前我们先了解下常量:常量创建之后不会改变,

如:1,2,3,'hello',"thank you"。

Python中没有预留关键字来标识常量的定义,其本质还是变量,定义常量一般用大写字母,实例代码:

2、字符串String

2.1创建字符串

我们使用单引号或者双引号( ' 或 " )来创建字符串,且Python中字符串不能改变,实例代码:

2.2字符串使用

字符串使用单/双引号是没有任何区别的,也可以相互嵌套使用,实例代码:

 

2.3三引号(''' 或者 """)用法

除了用以多行注释,还常用来定义多行多语句文档字符串,可以包含换行符、制表符以及其他特殊字符,实例代码:

 

HTML代码字符串:

 

从上面的实例中我们可以看出,三引号让程序员从引号和特殊字符串的泥潭里面解脱出来。

 

2.4 我们用反斜杠对特殊字符转义

反斜扛出现行尾,表示续行符;

(回车), (换行), '(单引号), "(双引号), \(转义)等等

如果不想让字符串中的特殊字符进行转义,可以在字符串前加r或R,

实例代码:

 

2.5字符串编解码

在Python3.x中所有的字符串都是Unicode字符串,且源码文件默认是UTF-8编码方式,UTF-8是unicode的一种实现方式,实例代码:

 

注意:如果中文数据是以gbk编码的,解码时也要对应的使用gbk去解码。

2.6用百分号 % 来表示格式化字符串和数字

常用的几种字符串格式化实例:

下面我们使用str.format()函数来格式化,实例代码:

 

2.7字符串索引和字符串截取

Python 中单字符也是作为一个字符串使用,使用方括号[ ]来截取字符串。

两种索引方式:正数代表从前往后索引,负数代表从后往前索引,

实例代码:

 

字符串截取时,[头下标:尾下标) 遵循“左闭右开”原则,也叫“包左不包右”。有两种索引方式就有两种截取方式,实例代码:

 

2.8字符串运算

 

2.9常用的几个字符串函数

 

2.10补充知识:f-string

在Python3.6+ 以后推荐使用 f-string来格式化,比%和str.formart()传统方式更加简单且性能也更优。用花括号{ } 来创建格式化,花括号里可以是变量,表达式,函数调用等;

 

f-string功能非常强大,对于自定义格式:对齐、宽度、符号、补零、精度、进制等功能。

f-string是格式化字符串的一种很好的新方法。与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快!

今天就开始使用f-string(后文称为F字符串) !

首先, 我们要聊以下在F字符串出现之前我们怎么实现格式化字符的。

旧时代的格式化字符串

 

在Python 3.6之前,有两种将Python表达式嵌入到字符串文本中进行格式化的主要方法:%-formatting和str.format()。您即将看到如何使用它们以及它们的局限性。

#1: %-formatting

这是Python格式化的OG(original generation),伴随着python语言的诞生。可以在Python文档中阅读更多内容。请记住,文档不建议使用%格式,其中包含以下注释:

“The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly).

Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.”

怎样使用 %-formatting

字符串对象具有使用%运算符的内置操作,可以使用它来格式化字符串。

name = "Eric""Hello, %s." % name# 输出'Hello, Eric.'

为了插入多个变量,必须使用这些变量的元组。以

name = "Eric"age = 74"Hello, %s. You are %s." % (name, age)# 输出'Hello, Eric. You are 74.'

为什么 %-formatting不好用

上面的代码示例足够易读。但是,一旦你开始使用几个参数和更长的字符串,将很快变得不太容易阅读。

first_name = "Eric"last_name = "Idle"age = 74profession = "comedian"affiliation = "Monty Python""Hello, %s %s. You are %s. You are a %s. You were a member of %s." %</div>(first_name, last_name, age, profession, affiliation)# 输出'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

这种格式不是很好,因为它是冗长的,会导致错误,比如不能正确显示元组或字典。

#2: str.format()

这种更新的工作方式是在Python 2.6中引入的。

怎样使用Use str.format()

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

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

"Hello, {}. You are {}.".format(name, age)# 输出'Hello, Eric. You are 74.'

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

"Hello, {1}. You are {0}-{0}.".format(age, name)# 输出'Hello, Eric. You are 74-74.'

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

person = {'name': 'Eric', 'age': 74}"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])# 输出'Hello, Eric. You are 74.'

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

"Hello, {name}. You are {age}.".format(**person)# 输出'Hello, Eric. You are 74.'

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

为什么 str.format() 并不好

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

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}.") </div>        .format(first_name=first_name, last_name=last_name, age=age, </div>               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开始加入标准库。

也称为“格式化字符串文字”,F字符串是开头有一个f的字符串文字,以及包含表达式的大括号将被其值替换。表达式在运行时进行渲染,然后使用__format__协议进行格式化。与

以下是f-strings可以让编程更轻松的一些方法。

简单例子:

语法与str.format()使用的语法类似,但较少细节啰嗦。

name = "Eric"age = 74f"Hello, {name}. You are {age}."# 输出'Hello, Eric. You are 74.'

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

F"Hello, {name}. You are {age}."# 输出'Hello, Eric. You are 74.'

任意表达式

由于f字符串是在运行时进行渲染的,因此可以将任何有效的Python表达式放入其中。

可以做一些非常简单的事情,就像这样:

f"{2 * 37}"# 输出'74'

可以调用函数

f"{name.lower()} is funny."# 输出'eric is funny.'

甚至可以使用带有f字符串的类创建对象。

class Comedian:    def __init__(self, first_name, last_name, age):        self.first_name = first_name        self.last_name = last_name        self.age = age     def __str__(self):        return f"{self.first_name} {self.last_name} is {self.age}."     def __repr__(self):        return f"{self.first_name} {self.last_name} is {self.age}. Surprise!"    new_comedian = Comedian("Eric", "Idle", "74")f"{new_comedian}"'Eric Idle is 74.'

__str __()和__repr __()方法处理对象如何呈现为字符串,因此您需要确保在类定义中包含至少一个这些方法。如果必须选择一个,请使用__repr __(),因为它可以代替__str __()。

__str __()返回的字符串是对象的非正式字符串表示,应该可读。__repr __()返回的字符串是官方表示,应该是明确的。调用str()和repr()比直接使用__str __()和__repr __()更好。

默认情况下,f字符串将使用__str __(),但如果包含转换标志!r,则可以确保它们使用__repr __():

f"{new_comedian}"'Eric Idle is 74.'f"{new_comedian!r}"'Eric Idle is 74. Surprise!'

多行f-string

多行字符串:

message = (f"Hi {name}. "        f"You are a {profession}. "        f"You were in {affiliation}.")message# 输出'Hi Eric. You are a comedian. You were in Monty Python.'

没必要将f放在多行字符串的每一行的前面。以下代码也能运行:

message = (f"Hi {name}. "        "You are a {profession}. "        "You were in {affiliation}.")message# 输出'Hi Eric. You are a {profession}. You were in {affiliation}.'

但是如果使用"""这将会发生什么:

message = f"""    Hi {name}.     You are a {profession}.     You were in {affiliation}. """ message# 输出'\n    Hi Eric. \n    You are a comedian. \n    You were in Monty Python.\n '

性能

f字符串中的f也可以代表“速度快”。

f-字符串比%-formatting和str.format()都快。f-字符串是运行时渲染的表达式,而不是常量值。以下是文档摘录:

“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with f, which contains expressions inside braces. The expressions are replaced with their values.” (Source)

在运行时,大括号内的表达式将在其自己的作用域中进行求值,然后将其与其余字符串组合在一起。

以下是速度比较:

%%timeitname = "Eric" age = 74 '%s is %s.' % (name, age)

202 ns ± 2.05 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeitname = "Eric" age = 74 '{} is {}.'.format(name, age)

244 ns ± 5.52 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeitname = "Eric" age = 74 '{name} is {age}.'

14.4 ns ± 0.0121 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

可以看到, 速度最快的就是f字符串.

Python f-Strings:Pesky细节

为什么F字符串很好,开始使用它们但请记住一些细节。

引号

您可以在表达式中使用各种类型的引号。只要确保在表达式中使用的f-字符串外部没有使用相同类型的引号即可。

以下写法都是正确的:

f"{'Eric Idle'}"'Eric Idle' f'{"Eric Idle"}''Eric Idle' f"""Eric Idle"""'Eric Idle' f'''Eric Idle''''Eric Idle' f"The \"comedian<span class="string">" is {name}, aged {age}."'The "comedian" is Eric, aged 74.'

字典

说在使用字典的时候。如果要为字典的键使用单引号,请记住确保对包含键的f字符串使用双引号。

以下代码是有效的:

comedian = {'name': 'Eric Idle', 'age': 74}f"The comedian is {comedian['name']}, aged {comedian['age']}."# 输出'The comedian is Eric Idle, aged 74.'

但是,以下代码就是一个语法错误:

f'The comedian is {comedian['name']}, aged {comedian['age']}.'# 输出  File "<ipython-input-40-cd7d8a3db23b>", line 1    f'The comedian is {comedian['name']}, aged {comedian['age']}.'                                    ^SyntaxError: invalid syntax

字典键周围使用与在f字符串外部使用相同类型的引号,则第一个字典键开头的引号将被解释为字符串的结尾。

大括号

为了使字符串出现大括号,您必须使用双大括号:

f"{{74}}"'{74}'

但是,如果使用三个以上的大括号,则可以获得更多大括号:

f"{{{{74}}}}"'{{74}}'

反斜杠

正如之前所看到的,可以在f字符串的字符串部分使用反斜杠转义符。但是,不能使用反斜杠在f字符串的表达式部分中进行转义:

f"{<span class="string">"Eric Idle\"}" # 输出  File "<ipython-input-43-35cb9fe0ccc1>", line 1    f"{\"Eric Idle\"}"                      ^SyntaxError: f-string expression part cannot include a backslash

lambda表达式

如果需要使用lambda表达式,解析f-字符串的方式会稍微复杂一些。

如果!, :或}不在括号,大括号,括号或字符串中,则它将被解释为表达式的结尾。由于lambda使用:,这可能会导致一些问题:

f"{lambda x: x * 37 (2)}"# 输出  File "<fstring>", line 1    (lambda x)            ^SyntaxError: unexpected EOF while parsing

可以通过将您的lambda嵌套在圆括号中来解决此问题:

f"{(lambda x: x * 37) (2)}"# 输出'74'

虽然仍然可以使用格式化字符串的较旧方式,但使用F字符串时可以更简洁,更易读且更方便的方式,既快速又不易出错。

 

posted @ 2019-05-18 15:10  在软件技术路上的行者  阅读(154)  评论(0编辑  收藏  举报