1.字符串处理函数
- upper(): 将字符串中的所有字符转换为大写。
s = "hello world" print(s.upper()) # 输出:HELLO WORLD
- lower(): 将字符串中的所有字符转换为小写。
s = "HELLO WORLD"
print(s.lower()) # 输出:hello world
-
strip(): 删除字符串前后的空格(或指定字符)。
s = " hello world " print(s.strip()) # 输出:hello world
-
split(): 根据指定的分隔符将字符串分割成多个子串,返回一个列表。
s = "apple,banana,orange"
print(s.split(",")) # 输出['apple', 'banana', 'orange']
-
join(): 将一个字符串列表(或元组)连接成一个单独的字符串。
s = ["apple", "banana", "orange"] print(",".join(s)) # 输出:apple,banana,orange
-
find(): 返回子串在字符串中首次出现的索引位置。
s = "hello world"
print(s.find("world")) # 输出:6
-
replace(): 在字符串中替换指定的子串。
s = "hello world" print(s.replace("world", "Python")) # 输出:hello Python
-
capitalize(): 将字符串的第一个字符转换为大写,其余为小写。
s = "hello world"
print(s.capitalize()) # 输出:Hello world
-
title(): 将字符串中每个单词的首字母转换为大写,其余为小写。
s = "hello world" print(s.title()) # 输出:Hello World
-
ljust(), rjust(): 在字符串的左侧或右侧填充指定的字符。
s = "hello"
print(s.ljust(10)) # 输出:hello (在左侧填充3个空格)
print(s.rjust(10)) # 输出: hello (在右侧填充3个空格)
- lstrip(), rstrip(): 删除字符串左侧或右侧的空格(或指定字符)。
s = " hello world "
print(s.lstrip()) # 输出:hello world (删除左侧的空格)
print(s.rstrip()) # 输出: hello world (删除右侧的空格)
- isalpha(), isdigit(), isalnum(), isspace(): 检查字符串是否只包含字母,数字,字母和数字,或空格。
s = "hello"
print(s.isalpha()) # 输出:True (只包含字母)
print(s.isdigit()) # 输出:False (不包含数字)
2.类型转换函数
-
list(), tuple(), dict(), set() 等:将其他类型转换为相应的容器类型。range(): 生成一个数字序列。
print(list("Hello")) # 输出:['H', 'e', 'l', 'l', 'o'] print(tuple([1, 2, 3])) # 输出:(1, 2, 3) print(dict(key1=value1, key2=value2)) # 输出:{'key1': 'value1', 'key2': 'value2'} print(set([1, 2, 3, 3])) # 输出:{1, 2, 3}
-
int(), float(), bool() ,str()等:将字符串或其他类型转换为相应的数值或布尔值。
print(int("123")) # 输出:123 print(float("3.14")) # 输出:3.14 print(bool("")) # 输出:False print(str(True)) # 输出:'True'
3.数学函数
3.1 计算
-
sum(), min(), max() 等:对容器中的元素进行计算。
numbers = [1, 2, 3, 4, 5] print(sum(numbers)) # 输出:15 print(min(numbers)) # 输出:1 print(max(numbers)) # 输出:5
3.2 保留小数数目
小数保留:
# 原始数字 num = 3.14159 # 保留四位小数 rounded_num = round(num, 4) print(rounded_num) # 输出:3.1416,对于整数只会输出1位小数
整数保留小数:
num = 123.456789 formatted_num = format(num, '.4f') print(formatted_num) # 输出 '123.4568' num = 123.456789 formatted_num = f"{num:.4f}" print(formatted_num) # 输出 '123.4568'
4.文件处理函数
-
open(): open()函数用于打开一个文件;
-
read(): read()函数用于从文件中读取内容。
-
write(): write()函数用于向文件中写入内容。
-
close(): close()函数用于关闭文件。在使用完文件后,关闭它,避免资源泄漏。
f = open('example.txt', 'r') # 打开一个文件进行读取 print(f.read()) f.close() f = open('example.txt', 'w')# 打开一个文件进行写入 f.write('Hello, World!') f.close()
-
with语句: with语句可以自动处理文件的打开和关闭。
-
readlines(): readlines()函数用于读取整个文件,并将其作为单独的行存储在列表中。
-
writelines(): writelines()函数用于向文件中写入一个字符串列表。每个字符串被写入新的一行。
-
seek(): seek()函数用于移动文件指针到指定位置
-
tell(): tell()函数用于返回当前文件指针的位置。
with open('example.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line)
lines = ['Hello, World!\n', 'Hello, Python!\n']
with open('example.txt', 'w') as f:
f.writelines(lines)
with open('example.txt', 'r') as f: # 将文件指针移动到文件开头
f.seek(0)
print(f.read()) # 输出文件的全部内容
with open('example.txt', 'r') as f: # 计算文件大小
f.seek(0, 2) # 移动到文件末尾
size = f.tell() # 获取文件大小
5.其它函数
5.1 enumerate
enumerate(): 将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(i, fruit) # 输出:0 apple, 1 banana, 2 cherry
5.2 filter
用于过滤序列,去除不符合特定条件的元素,返回由符合条件元素组成的新列表。它接受两个参数,一个是过滤函数(或lambda表达式),另一个是要过滤的序列。下面删除1-100中的素数:
def is_prime(n):
"""检查一个数是否是素数"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = int(n**0.5) + 1
for divisor in range(3, sqrt_n, 2):
if n % divisor == 0:
return False
return True
# 删除1-100的素数后的List
primes = list(filter(lambda x : not is_prime(x), range(1, 101)))
print(primes)
迭代器
Iter()函数用来将数组等创建成迭代器进行遍历。next()函数是用于迭代器或生成器的。它被用来获取迭代器的下一个项目,或者在生成器中生成下一个值。
l=[1,2,3,4]
it=iter(l)
while True:
try:
print(next(it))
except StopIteration:
break
生成器
在Python中,next()函数和yield关键字一起使用,可以实现生成器的功能。生成器是一种特殊的迭代器,它可以在需要时生成数据,而不是一次性将所有数据加载到内存中。
def odd():
print('1 s')
yield 1
print('2 s' )
yield 2
a=odd()
print(next(a)) #输出2
print(next(a)) #输出2