Python中字符串和列表的常用函数
字符串和列表是Python中最常用的两种数据类型之一,它们都有很多常用的函数可以进行操作。下面将介绍一些常用的字符串和列表函数。
## 字符串函数
### 1. len()
len()函数用于获取字符串的长度。
s = "Hello, world!" print(len(s)) # 输出:13
### 2. upper()和lower()
upper()函数用于将字符串中的小写字母转换为大写字母,lower()函数则相反,用于将字符串中的大写字母转换为小写字母。
s = "Hello, world!" print(s.upper()) # 输出:HELLO, WORLD! print(s.lower()) # 输出:hello, world!
### 3. find()和index()
find()函数用于查找字符串中是否包含某个子串,如果包含则返回该子串的起始位置,否则返回-1;index()函数与find()函数的功能相同,但如果子串不存在,则会抛出异常。
s = "Hello, world!"
print(s.find("world")) # 输出:7
print(s.index("world")) # 输出:7
print(s.find("python")) # 输出:-1
# print(s.index("python")) # 抛出异常:ValueError: substring not found
### 4. replace()
replace()函数用于将字符串中的某个子串替换为另一个字符串。
s = "Hello, world!"
print(s.replace("world", "Python")) # 输出:Hello, Python!
### 5. split()
split()函数用于将字符串根据指定的分隔符进行拆分,并返回一个列表。
s = "Hello, world!"
print(s.split(",")) # 输出:['Hello', ' world!']
### 6. join()
join()函数用于将列表中的字符串元素连接起来,返回一个新的字符串。
lst = ['Hello', 'world']
print(','.join(lst)) # 输出:Hello,world
### 7. strip()
strip()函数用于去除字符串两端的空白字符。
s = " Hello, world! " print(s.strip()) # 输出:Hello, world!
## 列表函数
### 1. len()
len()函数用于获取列表的长度。
lst = [1, 2, 3, 4, 5] print(len(lst)) # 输出:5
### 2. append()和extend()
append()函数用于向列表末尾添加一个元素,extend()函数则用于将一个列表的元素追加到另一个列表的末尾。
lst1 = [1, 2, 3] lst2 = [4, 5, 6] lst1.append(4) print(lst1) # 输出:[1, 2, 3, 4] lst1.extend(lst2) print(lst1) # 输出:[1, 2, 3, 4, 5, 6]
### 3. insert()和remove()
insert()函数用于在指定的位置插入一个元素,remove()函数则用于移除列表中的某个元素。
lst = [1, 2, 3, 4, 5] lst.insert(0, 0) print(lst) # 输出:[0, 1, 2, 3, 4, 5] lst.remove(3) print(lst) # 输出:[0, 1, 2, 4, 5]
### 4. sort()和reverse()
sort()函数用于对列表进行排序,reverse()函数用于将列表元素反转。
lst = [5, 3, 4, 1, 2] lst.sort() print(lst) # 输出:[1, 2, 3, 4, 5] lst.reverse() print(lst) # 输出:[5, 4, 3, 2, 1]
### 5. index()和count()
index()函数用于查找某个元素在列表中的 个出现位置的索引,count()函数用于统计某个元素在列表中出现的次数。
lst = [1, 2, 3, 1, 4, 1] print(lst.index(1)) # 输出:0 print(lst.count(1)) # 输出:3
### 6. slice操作
slice操作用于获取列表的一个子列表。
lst = [1, 2, 3, 4, 5] print(lst[1:3]) # 输出:[2, 3] print(lst[:-1]) # 输出:[1, 2, 3, 4]
以上是字符串和列表的一些常用函数,它们能够极大地帮助我们处理字符串和列表的操作。
