[python] str
一、移除字符串中所有非字母数字字符
- 使用正则表达式
import re
string_value = "alphanumeric@123__"
cleaned_string = re.sub(r'[\W_]', '', string_value)  
# 或 r'[^a-zA-Z0-9]'
print(cleaned_string)  
# 输出: alphanumeric123
- 使用**str.isalnum()**方法
string_value = "Hello, World! 123"
cleaned_string = ''.join(char for char in string_value if char.isalnum())
print(cleaned_string)  
# 输出: HelloWorld123
二、lower()方法
lower() 是Python字符串的内置方法,用于将字符串中的所有大写字母转换为小写字母。它不会修改原始字符串,而是返回一个新的字符串。
text = "Hello, World!"
lower_text = text.lower()
print(lower_text)   
# 输出: hello, world! 
注意事项
- lower()只对字母字符有效,数字和符号不受影响。
- 原始字符串不会被修改,lower()返回的是新字符串。
- 对于非英文字母(如中文、数字、符号),lower()不会进行任何转换。
三、find()
Python的字符串find()方法用于在字符串中查找子字符串的位置,以下是详细介绍:
- 基本语法
 str.find(sub, start, end)
- sub:要查找的子字符串(必需)。
- start:可选,指定搜索的起始索引(默认为0)。
- end:可选,指定搜索的结束索引(默认为字符串末尾)
- 返回值
- 找到子字符串时,返回其首次出现的起始索引(从0开始)。
- 未找到时返回 -1(与index()方法不同,后者会抛出ValueError)
- 示例代码
text = "Hello, world!" 
# 查找子字符串
index = text.find("world")   返回7
not_found = text.find("Python")   # 返回-1 
# 指定搜索范围
index_range = text.find("o", 5, 10)   # 在索引5-10间查找"o" 
- 关键特性
- 区分大小写:如查找"hello"和"Hello"结果不同。
- 范围限定:通过start和end可限制搜索区间。
- 多次查找:结合循环可找到所有匹配位置:
text = "banana"  
start = 0  
while (start := text.find("a", start)) != -1:      print(f"Found at index: {start}")      start += 1 
- 与相关方法的对比
- in运算符:仅检查子字符串是否存在(返回布尔值),不返回位置。
- rfind():从右向左查找,返回最后一次出现的索引。
- 注意事项
- 若start > end,直接返回-1。
