CodeGym /课程 /Python SELF ZH /字符串操作

字符串操作

Python SELF ZH
第 10 级 , 课程 4
可用

12.1 方法列表

在Python中,字符串数据类型有一个丰富的方法集合,让字符串操作既方便又强大。以下是一些最受欢迎的string类的方法:

方法 描述
strip() 去掉字符串开头和结尾的空格。
lower() 将字符串中的所有字符转换为小写。
upper() 将字符串中的所有字符转换为大写。
replace(old, new) 将所有old子字符串替换为new子字符串。
split(separator) 根据指定的分隔符将字符串分割为子字符串列表。
join(iterable) 使用分隔符将字符串集合合并为一个字符串。
find(substring) 返回子字符串的第一个出现的索引,如果未找到则返回-1
index(substring) 返回子字符串的第一个出现的索引,如果未找到则抛出异常。
format() 格式化字符串,用值替换大括号。
startswith(prefix) 检查字符串是否以prefix子字符串开头。
endswith(suffix) 检查字符串是否以suffix子字符串结尾。

注意,str类型的对象在创建后是不可改变的。所有修改字符串的函数实际上都会返回一个新对象。旧的对象保持不变。

12.2 最受欢迎的方法

我们来研究几个最简单和最受欢迎的方法。

方法 strip():

去掉字符串开头和结尾的空格。


text = "  hello world!  "
cleaned_text = text.strip()
print(cleaned_text)  # 输出: "hello world!"
        

方法 lower():

将字符串中的所有字符转换为小写。


text = "Hello World!"
lower_text = text.lower()
print(lower_text)  # 输出: "hello world!"
            
        

方法 upper():

将字符串中的所有字符转换为大写。


text = "Hello World!"
upper_text = text.upper()
print(upper_text)  # 输出: "HELLO WORLD!"
        

方法 split(separator):

根据指定的分隔符将字符串分割为子字符串列表。


text = "one,two,three"
parts = text.split(',')
print(parts)  # 输出: ['one', 'two', 'three']
        

方法 join(iterable):

使用分隔符将字符串集合合并为一个字符串。


parts = ['one', 'two', 'three']
joined_text = ','.join(parts)
print(joined_text)  # 输出: "one,two,three"
        

重要! 注意,join()方法是在分隔符字符串上调用的!

这些方法是处理和操作Python中的文本数据的主要工具。

12.3 查找和替换子字符串

还有一些常用的方法用于在字符串中查找和替换子字符串。

方法 find(substring):

返回子字符串在字符串中的第一个出现的索引,如果未找到则返回-1


text = "hello world"
index = text.find("world")
print(index)  # 输出: 6
        

方法 index(substring):

类似于find,但如果未找到子字符串则抛出ValueError异常。


text = "hello world"
try:
    index = text.index("world")
    print(index)  # 输出: 6
except ValueError:
    print("子字符串未找到")
        

方法 replace(old, new):

将所有old子字符串替换为new子字符串。


text = "hello world"
replaced_text = text.replace("world", "everyone")
print(replaced_text)  # 输出: "hello everyone"
        

方法 startswith(prefix):

检查字符串是否以指定的前缀开始。


text = "hello world"
print(text.startswith("hello"))  # 输出: True 
        

方法 endswith(suffix):

检查字符串是否以指定的后缀结尾。


text = "hello world"
print(text.endswith("world"))  # 输出: True
        

这些方法对于各种查找、替换和验证操作非常有用,简化了文本数据的处理。

2
任务
Python SELF ZH, 第 10 级, 课程 4
已锁定
清理
清理
2
任务
Python SELF ZH, 第 10 级, 课程 4
已锁定
重组。
重组。
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION