0

30天Python入门到进阶——第3天:数据类型(Ⅱ)

 1 year ago
source link: https://blog.51cto.com/u_13237322/5693610
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
30天Python入门到进阶——第3天:数据类型(Ⅱ)_python教程

昨天讲到了字符串的基本定义、连接和类型转换,继续昨天学习的字符串数据类型,今天我探索了其他一些特性。

格式化字符串

字符串格式化是一个简洁的功能,它允许我们动态更新字符串内容。假设我们从服务器获取用户信息,并希望根据该信息显示自定义消息。第一个想法是应用字符串连接,例如:

first_name = 'Tom'
last_name = 'Cruise'
welcome_message = "Welcome" + " " + first_name + " " + last_name
print(welcome_message) # Welcome Tom Cruise

如果我们有更多变量,那么动态字符串可能会有点难以阅读。如果我们有其他类型的数据,那么我们还需要将它们转换为字符串。使用格式化字符串有一种更简洁的方法。

first_name = 'Tom'
last_name = 'Cruise'
welcome_message = f'Welcome {first_name} {last_name}'
print(welcome_message) # Welcome Tom Cruise

字符串前面的​​f​​表示格式化的字符串。动态值放置在 ​​{}​​中,这是一种更简洁的语法。JavaScript 等价物是 ES6 中引入的字符串插值或模板字符串。比如下面:

firstName = 'Tom';
lastName = 'Cruise';
welcomeMessage = `Welcome ${firstName} ${lastName}`;
console.log(welcomeMessage) // Welcome Tom Cruise

字符串索引

Python中的字符串只是字符的有序集合。所以我们可以用它做很多很酷的把戏。我们可以访问字符串的字符,选择子字符串,反转字符串,而且非常容易。它也称为字符串切片。

language = 'python'
first_character = language[0] # indexing starts from 0
second_character = language[1]
print(first_character) # p
print(second_character) # y
# Strings can be manipulated easily with this syntax [start:stop:step-over]
range_1 = language[0:2] # here it starts from index 0 and ends at index 1
range_2 = language[0::1] # starts at 0, stops at end with step over 1
range_3 = language[::2] # starts at 0, till end with step 2
range_4 = language[1:] # starts at index 1 till end of string
range_5 = language[-1] # selects last character
range_6 = language[-2] # second last character
reverse_string = language[::-1] # starts from end and reverses the string
reverse_string_2 = language[::-2] # reverses string and skips 1 character

print(range_1) # py
print(range_2) # python
print(range_3) # pto
print(range_4) # ython
print(range_5) # n
print(range_6) # o
print(reverse_string) # nohtyp
print(reverse_string_2) # nhy

字符串本质上是不可变的。这意味着字符串的值不能被篡改或更改。

favorite_website = 'dev.to'
favorite_website[0] = 'w'
print(favorite_website) # TypeError: 'str' object does not support item assignment

内置字符串函数和方法

Python有一些内置函数和方法来对字符串数据类型进行操作。函数通常是可以像​​print()​​、​​round()​​那样独立调用的操作,而方法只是作为对象的一部分并用​​.​​运算符调用。

quote = 'javascript is awesome'
print(len(quote)) # 21 (len calculates total no of characters)
new_quote = quote.replace('javascript', 'python')
print(new_quote) # python is awesome
capitalize = new_quote.capitalize()
print(capitalize) # Python is awesome
upper_case = new_quote.upper()
print(upper_case) # PYTHON IS AWESOME

print(quote) # javascript is awesome (Note: Strings are immutable!)

string.capitalize()

把字符串的第一个字符大写

string.center(width)

返回一个原字符串居中,并使用空格填充至长度width的新字符串

string.count(str, beg=0, end=len(string))

返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数

bytes.decode(encoding='UTF-8', errors='strict')

Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象

string.encode(encoding='UTF-8', errors='strict')

以 encoding 指定的编码格式编码 string,编码的结果是一个bytes对象。如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'

string.endswith(obj, beg=0, end=len(string))

检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.

string.expandtabs(tabsize=8)

把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8。

string.find(str, beg=0, end=len(string))

检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1

string.format()

格式化字符串

string.index(str, beg=0, end=len(string))

跟find()方法一样,只不过如果str不在 string中会报一个异常.

string.isalnum()

如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回False

string.isalpha()

如果 string 至少有一个字符并且所有字符都是字母则返回True,否则返回False

string.isdecimal()

如果 string 只包含十进制数字则返回 True 否则返回 False.

string.isdigit()

如果 string 只包含数字则返回 True 否则返回 False.

string.islower()

如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False

string.isnumeric()

如果string中只包含数字字符,则返回True,否则返回False

string.isspace()

如果 string 中只包含空格,则返回 True,否则返回 False.

string.istitle()

如果 string 是标题化的(见 title())则返回 True,否则返回 False

string.isupper()

如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False

string.join(seq)

以string作为分隔符,将seq中所有的元素(的字符串表示)合并为一个新的字符串

string.ljust(width)

返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串

string.lower()

转换 string 中所有大写字符为小写.

string.lstrip()

截掉 string 左边的空格

string.maketrans(intab, outtab)

maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

max(str)

返回字符串 str 中最大的字母。

min(str)

返回字符串 str 中最小的字母。

string.partition(str)

有点像 find()和 split()的结合体,从 str 出现的第一个位置起,把 字 符 串 string 分 成 一 个 3 元 素 的 元 组 (string_pre_str,str,string_post_str),如果 string 中不包含str 则 string_pre_str == string.

string.replace(str1, str2, num=string.count(str1))

把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次.

string.rfind(str, beg=0,end=len(string))

类似于find()函数,不过是从右边开始查找.

string.rindex( str, beg=0,end=len(string))

类似于 index(),不过是从右边开始.

string.rjust(width)

返回一个原字符串右对齐,并使用空格填充至长度width的新字符串

string.rpartition(str)

类似于 partition()函数,不过是从右边开始查找.

string.rstrip()

删除 string 字符串末尾的空格.

string.split(str="", num=string.count(str))

以str为分隔符切片 string,如果 num有指定值,则仅分隔num个子字符串

string.splitlines([keepends])

按照行('\r','\r\n',\n')分隔,返回一个包含各行作为元素的列表,如果参数keepends为False,不包含换行符,如果为True,则保留换行符。

string.startswith(obj, beg=0,end=len(string))

检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查.

string.strip([obj])

在 string 上执行 lstrip()和 rstrip()

string.swapcase()

翻转 string 中的大小写

string.title()

返回"标题化"的string,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())

string.translate(str, del="")

根据 str 给出的表(包含 256 个字符)转换 string 的字符,要过滤掉的字符放到 del 参数中

string.upper()

转换 string 中的小写字母为大写

string.zfill(width)

返回长度为 width 的字符串,原字符串 string右对齐,前面填充0

字符串是Python中和列表、字典同样重要的数据类型,对它的操作特别多,因此内置了很多方法。每当你要处理字符串的时候,不妨来这里查查,或许就有原生的方法,不用你自己去写了。

对字符串的操作方法那么多,是不是需要每个都背下来呢?能背最好,背不了的话至少需要知道下面几个:

  • encode() # 编码成bytes类型
  • find() # 查找子串
  • index() # 获取下标
  • replace() # 替换子串
  • len(string) # 返回字符串长度,Python内置方法,非字符串方法。
  • lower() # 小写字符
  • upper() # 大写字符
  • split() # 分割字符串
  • strip() # 去除两端的指定符号
  • startswith() # 字符串是否以xxx开头
  • endswith() # 字符串是否以xxx结尾

对于错、0和1、正与反,都是传统意义上的布尔类型。

但在Python语言中,布尔类型只有两个值,​​True​​False​​。请注意,是英文单词的对与错,并且首字母要大写,不能其它花式变型。

所有计算结果,或者调用返回值是True或者False的过程都可以称为布尔运算,例如比较运算。布尔值通常用来判断条件是否成立。

is_cool = True
is_dirty = False
print(10 > 9) # True

Python内置的​​bool()​​函数可以用来测试一个表达式的布尔值结果。

下面一些例子的结果,可能让你感到惊讶,但事实就是如此,请坦然接受。

>>> True
True
>>> False
False
>>> 3 > 2
True
>>> 3 > 5
False
>>> 3 in [1,2,3]
True
>>> 3 == 9/3
True
>>> 3 is "3"
False

为什么​​3 is "3"​​是错误的呢?因为一个是整数一个是字符串,is运算符比较的是对象,当然是错误的。

and、or和not运算

and运算是与运算,只有所有都为True,and运算的结果才是True:

>>> True and True
True
>>> True and False
False
>>> False and False
False
>>> 5 > 3 and 3 > 1
True

or运算是或运算,只要其中有一个为True,or运算结果就是True:

>>> True or True
True
>>> True or False
True
>>> False or False
False
>>> 5 > 3 or 1 > 3
True

not运算是非运算,它是单目运算符,把True变成False,False变成True:

>>> not True
False
>>> not False
True
>>> not 1 > 2
True

再开下脑洞,布尔类型还能做别的运算吗?试试就知道了!

>>> True > False
True
>>> True < False
False
>>> True >=False
True
>>> True -1
0
>>> True + 1
2
>>> True *3
3
>>> False -1
-1

真的可以!比较运算,四则运算都没有问题。并且在做四则运算的时候,明显把True看做1,False看做0。往往是我们不知道的细节,有时候给我们带来巨大的困扰和疑惑。更多的运算种类支持,请大家自行测试。

注释是用代码编写的语句,以增强其可读性。在 Python 中,它们是用​​#​​符号后跟注释编写的。解释器会忽略注释,仅用于代码可读性目的。我已经在代码示例中使用它们来打印输出或添加一些注释。根据良好的编程实践,我们应该尽量让我们的代码像阅读英语一样具有可读性,并且仅在需要时才添加注释,因为带有过多注释的臃肿代码可能会适得其反。

# This is not a very useful comment but written just for the sake of demonstration

我们写的程序里,不光有代码,还要有很多注释。注释有说明性质的、帮助性质的,它们在代码执行过程中相当于不存在,透明的,不参与任何工作。但在代码维护、解释、测试等等方面,发挥着不可或缺的重要作用。每一位程序员都要尽量写出高质量的注释。具体的注释专题,有大量的高水平文章和论述,请自行搜索并学习。这里,我们只讨论Python中注释的方法。

Python中,以符号“#”为单行注释的开始,从它往后到本行的末尾,都是注释内容。

#!/usr/bin/python3
# 下面这个方法的作用是…..
# 第一个注释
# 我是单行注释

# 这是一个空的函数,它什么都不干。本条注释也是句废话。
def main():
pass # pass表示占位,什么都不做。那我为什么要注释它呢???

Python没有真正意义上的多行注释(块注释)语法。你只能在每行的开头打上#号,然后假装自己是个多行注释。

# 第一行注释
# 第二行注释
# 第三行注释
def func():
print("这是一个悲伤的故事!")

在某些特定的位置,用三引号包括起来的部分,也被当做注释。但是,这种注释有专门的作用,用于为__doc__提供文档内容,这些内容可以通过现成的工具,自动收集起来,形成帮助文档。比如,函数和类的说明文档:

def func(a, b):
"""
这个是函数的说明文档。
:param a: 加数
:param b: 加数
:return: 和
"""
return a + b


class Foo:
"""
这个类初始化了一个age变量
"""
def __init__(self, age):
self.age = age

需要强调的是这类注释必须紧跟在定义体下面,不能在任意位置。

列表是一种重要的数据类型。它们是有组织的对象集合。它也是一种数据结构,意味着一个容器,可以为不同目的以某种特定格式组织数据。它们就像来自 JavaScript 或其他编程语言领域的数组。它们用 表示​​[ ]​​。它们可用于将相同或不同的数据类型存储在一起,列表中的每个元素都被分配一个数字作为索引,用来表示该元素在列表内所排在的位置。第一个元素的索引是0,第二个索引是1,依此类推。

Python的列表是一个有序可重复的元素集合,可嵌套、迭代、修改、分片、追加、删除,成员判断。

从数据结构角度看,Python的列表是一个可变长度的顺序存储结构,每一个位置存放的都是对象的指针。

favorite_languages = ['javascript', 'python', 'typescript']
shopping_cart_items = ['pen','toothbrush', 'sanitizer','eraser']
random_things = ['football', 123, True, 'developer', 777]

first_item = shopping_cart_items[0]
print(first_item) # 'pen'

与字符串类似,列表可以被切片。但是,与字符串不同,列表是可变的,这意味着它们的数据可以更改。

soccer_stars = ['ronaldo', 'messi','ibrahimovic','zidane','beckham']
soccer_stars[0] = 'suarez'
print(soccer_stars) # ['suarez', 'messi','ibrahimovic','zidane','beckham']
range = soccer_stars[0:3]
print(range) # ['suarez', 'messi', 'ibrahimovic']
print(soccer_stars) # ['suarez', 'messi','ibrahimovic','zidane','beckham']
# Note : Slicing lists does not mutate them

clone = soccer_stars[:] # copies the list. Commonly used in Python
print(clone) # ['suarez', 'messi','ibrahimovic','zidane','beckham']
reverse_order = soccer_stars[::-1] # reverses the order of data
print(reverse_order) # ['beckham', 'zidane', 'ibrahimovic', 'messi', 'suarez']

列表可以是多维的。我上面提到的列表示例都是一维或一维的。但是,我们可以在列表中包含列表。所以一个二维列表看起来像这样:

matrix_2 = [[1,3,2], [1,3,2], [2,3,4], [2,3,5]]
first_item = matrix_2[0]
print(first_item) # [1,3,2]
first_item_first_element = matrix_2[0][0] # or first_item[0]
print(first_item_first_element) # 1

我们可以类似地在列表中嵌套任意数量的列表,以创建类似于我们在小学学习的数学中的矩阵的不同维度矩阵。这种矩阵数据有助于存储图像等复杂数据,并用于机器学习模型。稍后探索它们并详细了解它们的实际应用会非常有趣。

好了,今天就学习这么多,好好消化一下,明天将继续学习列表的其余概念,例如它的功能和方法以及其他模式,然后学习其余的数据类型字典、元组、集合和None。我对逐渐探索这些数据结构产生了极大的兴趣。希望你在跟随的同时也发现它们很酷。让我们明天再见面吧!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK