您的位置:首页 > 房产 > 家装 > 零基础学习Python(七)

零基础学习Python(七)

2024/10/6 8:35:47 来源:https://blog.csdn.net/weixin_46628668/article/details/141575763  浏览:    关键词:零基础学习Python(七)

1. 字符串常用方法

lower()、upper():转换为小写字符串、大写字符串

split(str):按照指定字符串str进行分割,结果为列表:

email = "123@qq.com"
print(email.split("@"))
['123', 'qq.com']

count(str):统计str字符串出现的次数:

s = "hello"
print(s.count("o"))
1

find(str):查找str字符串首次出现的位置,如果没有,则为-1:

s = "hello"
print(s.find("l"))
print(s.find("p"))
2
-1

index(str):与find类似,区别在于如果字符串没有找到,则报错

startswith(str)、endswith(str):是否以str开头、是否以str结尾

replace(old, new):使用new字符串替换所有的old字符串:

print("hello".replace("o", "p"))
hellp

center(width, fillchar):在指定的宽度范围内居中,并可以使用fillchar进行填充:

print("HelloWorld".center(20))

print("HelloWorld".center(20, "*"))

join(iter):将可迭代对象iter每个元素通过该字符串相连:

print(".".join("hello"))
h.e.l.l.o

strip(chars):去掉左侧和右侧的chars中包含的字符,chars不穿则默认去除空格:

print("    Hello  World    ".strip())
Hello  World
print("ld-HelloWorld".strip("dl"))
-HelloWor

lstrip(chars)、rstrip(chars):去掉左侧的chars中包含的字符、去掉右侧的chars中包含的字符

2. 格式化字符串的三种方式

占位符方式:

name = "马冬梅"
age = 18
score = 98.5
print('姓名:%s,年龄:%d,分数:%.1f' % (name, age, score))
姓名:马冬梅,年龄:18,分数:98.5

f-string方式(Python 3.6之后的方式):

print(f'姓名:{name}, 年龄: {age}, 分数: {score}')
姓名:马冬梅,年龄:18,分数:98.5

format方式:

print('姓名:{0}, 年龄: {1}, 分数: {2}'.format(name, age, score))
姓名:马冬梅,年龄:18,分数:98.5

format方式中的大括号中的0/1/2是format参数对应的索引位置,实际上也可以这样写: 

print('姓名:{2}, 年龄: {0}, 分数: {1}'.format(age, score, name))

 3. 字符串的编码与解码

 字符串的编码与解码本质上是字符串与字节类型的转换。编码使用encode方法(默认编码方式是utf-8),解码使用decode方法:

s = "伟大的中国梦"
code = s.encode("utf-8")
print(code)
print(code.decode("utf-8"))

code是字节(bytes)类型。 

4. 字符串的验证

isdigit():所有字符是否都是数字,必须为阿拉伯数字

isnumeric(): 所有字符是否都是数字,可以为阿拉伯数字、罗马数字、中文数字

isalpha():所有字符是否都是字母,包括中文字符

islower():所有字符是否都是小写

isupper():所有字符是否都是大写

istitle():所有单词是否首字母大写

print("一二三".isnumeric())
print("壹贰叁".isnumeric())
print("中文和English".isalpha())
print("Hello World".istitle())
print("Hello world".istitle())
True
True
True
True
False

 5. 正则表达式

re.match函数从字符串的起始位置开始匹配,如果匹配成功,结果为Match对象,否则为None

import re
pattern = '\d+\.\d+'  #匹配一个或多个数字.一个或多个数字
print(re.match(pattern, '3.11'))
print(re.match(pattern, 'd3.11'))
<re.Match object; span=(0, 4), match='3.11'>
None

继续查看match对象的详细属性: 

m = re.match(pattern, '3.11')
print("匹配的起始位置", m.start())
print("匹配的结束位置", m.end())
print("匹配的区间", m.span())
print("匹配的数据", m.group())
匹配的起始位置 0
匹配的结束位置 4
匹配的区间 (0, 4)
匹配的数据 3.11

re.search函数搜索整个字符串匹配,只匹配第一个,如果匹配成功,结果为Match对象,否则为None

import re
pattern = '\d+\.\d+'  #匹配一个或多个数字.一个或多个数字
print(re.search(pattern, 'def3.11 & 2.7'))
<re.Match object; span=(3, 7), match='3.11'>

re.findall函数搜索整个字符串匹配,匹配所有,返回一个列表,如果没匹配,就是一个空列表(不是None)

print(re.findall(pattern, 'def3.11 & 2.7'))
['3.11', '2.7']

re.sub函数用于实现字符串中指定子串的替换

import re
pattern = '\d+\.\d+'  #匹配一个或多个数字.一个或多个数字
print(re.sub(pattern, '*', 'def3.11 & 2.7'))
def* & *

 re.split函数用于按照指定字符串来分割原始字符串

import re
pattern = '\d+\.\d+'  #匹配一个或多个数字.一个或多个数字
print(re.split(pattern, 'def3.11 & 2.7'))
['def', ' & ', '']

6. 习题

1个英文字符是1个字符,1个中文字符也是1个字符,只不过1个英文字符是1个字节,utf-8编码下,1个中文字符是3个字节,gbk编码下,1个中文字符是2个字节。

7. 内置函数

divmod:获取商和余数

x, y = divmod(13, 5)
print(x, y)
2 3

sorted:对可迭代对象进行排序,返回一个新的对象,不改变原对象中的元素顺序:

l = [3, 1, 44, 23]
print(sorted(l))
[1, 3, 23, 44]

reversed:反转序列

l = [3, 1, 44, 23]
print(list(reversed(l)))
[23, 44, 1, 3]

all:判断迭代器中所有元素的布尔值是否都为True

l1 = [3, 1, 44, 23, {}]
l2 = [3, 1, 44, 23, {2}]
print(all(l1))
print(all(l2))
False
True

any:判断迭代器中是否有元素的布尔值为True

l1 = [3, 1, 44, 23, {}]
l2 = [{}, (), False]
print(any(l1))
print(any(l2))
True
False

filter:通过指定条件过滤迭代器元素

l = [1, 2, 3, 4]
print(list(filter(lambda x: x % 2 == 0, l)))
[2, 4]

map:通过指定函数映射迭代器元素

l = [1, 2, 3, 4]
print(list(map(lambda x: x * 2, l)))
[2, 4, 6, 8]

8. 类和对象的特殊属性和方法

class A:passclass B:passclass C(A, B):def __init__(self, name, age):self.name = nameself.age = agea = A()
b = B()
c = C("zhangsan", 20)print("a的属性字典", a.__dict__)
print("b的属性字典", b.__dict__)
print("c的属性字典", c.__dict__)
a的属性字典 {}
b的属性字典 {}
c的属性字典 {'name': 'zhangsan', 'age': 20}
print("a所属的类", a.__class__)
print("b所属的类", b.__class__)
print("c所属的类", c.__class__)
a所属的类 <class '__main__.A'>
b所属的类 <class '__main__.B'>
c所属的类 <class '__main__.C'>
print("A的父类元祖", A.__bases__)
print("B的父类元祖", B.__bases__)
print("C的父类元祖", C.__bases__)
print("A的父类", A.__base__)
print("B的父类", B.__base__)
print("C的父类", C.__base__)
A的父类元祖 (<class 'object'>,)
B的父类元祖 (<class 'object'>,)
C的父类元祖 (<class '__main__.A'>, <class '__main__.B'>)
A的父类 <class 'object'>
B的父类 <class 'object'>
C的父类 <class '__main__.A'>
print("A类的层次结构", A.__mro__)
print("B类的层次结构", B.__mro__)
print("C类的层次结构", C.__mro__)
A类的层次结构 (<class '__main__.A'>, <class 'object'>)
B类的层次结构 (<class '__main__.B'>, <class 'object'>)
C类的层次结构 (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
print("A类的子类", A.__subclasses__())
print("B类的子类", B.__subclasses__())
print("C类的子类", C.__subclasses__())
A类的子类 [<class '__main__.C'>]
B类的子类 [<class '__main__.C'>]
C类的子类 []

注意,__subclasses__()是一个方法,不是属性

9. 对象的浅拷贝与深拷贝

浅拷贝:拷贝出来的对象的属性与原对象是一个地址空间的

深拷贝:拷贝出来的对象的属性与原对象不是一个地址空间的

import copyb = B()
bcopy = copy.copy(b)  #浅拷贝
bdeepcopy = copy.deepcopy(b)   #深拷贝

 10. random模块的简单使用

seed函数时生成随机数种子,如果不传参,则默认取当前系统时间,如果随机数种子相同,那么生成的随机数也相同。 

random.seed(10)
print(random.random())
print(random.randint(1, 10))

多次执行random.random和random.randint函数,发现结果一样:

0.5714025946899135
7

randrange用于产生m与n之间的步长为k的随机数:

print(random.randrange(1, 10, 3))
print(random.randrange(1, 10, 3))
print(random.randrange(1, 10, 3))
print(random.randrange(1, 10, 3))
print(random.randrange(1, 10, 3))
print(random.randrange(1, 10, 3))
7
7
7
4
7
1

choice函数用于从序列中随机选取一个数:

print(random.choice(range(1, 10)))
print(random.choice(range(1, 10)))
print(random.choice(range(1, 10)))
print(random.choice(range(1, 10)))
print(random.choice(range(1, 10)))
7
4
2
3
7

shuffle函数用于随机打乱序列的顺序:

li = [1, 2, 3, 4, 5, 6]
random.shuffle(li)
print(li)
[5, 6, 1, 2, 4, 3]

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com