Python —— 常用的字符串方法
Python —— 常用的字符串方法
- 引言
- 字符串大小写转换方法
- `str.upper()`
- `str.lower()`
- `str.capitalize()`
- `str.title()`
- `str.swapcase()`
- `str.casefold()`
- 字符串查找与替换方法
- `str.find(sub[, start[, end]])`
- `str.rfind(sub[, start[, end]])`
- `str.index(sub[, start[, end]])`
- `str.rindex(sub[, start[, end]])`
- `str.replce(old, new[, count])`
- `str.startswith(prefix[, start[, end]])`
- `str.endswith(suffix[, start[, end]])`
- `str.count(sub[, start[, end]])`
- 字符串分割与连接方法
- `strt.split(sep=None, maxsplit=-1)`
- `str.rsplit(sep=None, maxsplit=-1)`
- `str.splitlines([keepends])`
- `str.join(iterable)`
- 字符串修剪与填充方法
- `str.strip([chars])`
- `str.lstrip([chars])`
- `str.rstrip([]chars)`
- `str.center(width[, fillchar])`
- `str.ljust(width[, fillchar])`
- `str.rjust(width[, fillchar])`
- `str.zfill(width)`
- 字符串检查方法
- `str.isalpha()`
- `str.isdigit()`
- `str.isalnum`
- `str.islower()`
- `str.upper()`
- `str.isspace()`
- `str.isnumeric()`
- `str.isidentifier()`
- 字符串转换方法
- `str.isascii()`
- `str.isdecimal()`
- `str.isprineable()`
- `str.format(*args, **kwargs)`
- `f-字符串(Python 3.6+)`
- `str.format_map(mapping)`
引言
字符串是由零个或多个字符组成的有限序列,字符串不可修改。
字符串大小写转换方法
str.upper()
将字符串中所有字母转换为大写。
text = "Hello, World!"
print(text.upper()) # 输出: HELLO, WORLD!
str.lower()
将字符串中的所有字母转换为小写。
text = "Hello, World!"
print(text.lower()) # 输出: hello, world!
str.capitalize()
将字符串的第一个字符转换为大写,其余字符转换为小写。
text = "hello WORLD"
print(text.capitalize()) # 输出: Hello world
str.title()
将字符串中每个单词的首字母转换为大写。
text = "hello world"
print(text.title()) # 输出: Hello World
text = "43re he2343llo sdf wo \md!"
print(text.title())
# 输出:43Re He2343Llo Sdf Wo \Md!
str.swapcase()
将字符串中大写字母转换为小写,小写字母转换为大写。
text = "Hello, World!"
print(text.swapcase()) # 输出: hELLO, wORLD!
str.casefold()
将字符串转换为小写,且比lower()更强大,适用于去除大小写差异进行比较。
text = "Straße"
text_1 = "STRASSE"
print(text.lower() == text_1.lower()) # False
print(text.casefold() == text_1.casefold()) #True
str.lower():适用于简单的小写转换,主要处理标准的ASCII大写字母。
str.casefold():更为强大和全面,适用于不区分大小写的比较和多语言环境,能够处理更多特殊字符和语言特有的大小写规则。
字符串查找与替换方法
str.find(sub[, start[, end]])
查找子字符串sub在字符串中的位置,返回最低索引。如果未找到,返回-1。(方括号[]表示可选参数)
text = "Hello, World!"
print(text.find("World")) # 输出: 7
print(text.find("Python")) # 输出: -1
print(text.find("o", 6, 10)) # 输出: 8
str.rfind(sub[, start[, end]])
从右侧查找子字符串sub,返回最高索引。如果未找到,返回-1。
text = "Hello, World! Hello!"
print(text.rfind("Hello")) # 输出: 14
str.index(sub[, start[, end]])
类似find(),但如果未找到子字符串,会引发ValueError异常。
text = "Hello, World!"
print(text.index("World")) # 输出: 7
# print(text.index("Python")) # 会引发 ValueError
str.rindex(sub[, start[, end]])
类似rfind(),但如果未找到子字符串,会引发ValueError异常。
text = "Hello, World! Hello!"
print(text.rindex("Hello")) # 输出: 14
# print(text.rindex("Python")) # 会引发 ValueError
str.replce(old, new[, count])
将字符串中的old子字符串替换为new,可指定替换的次数count。
text = "Hello, World!"
print(text.replace("World", "Python")) # 输出: Hello, Python!
print(text.replace('l', '*', 2)) # 输出: He**o, World!
str.startswith(prefix[, start[, end]])
判断字符串是否以指定的前缀 prefix开始。
text = "Hello, World!"
print(text.startswith("Hello")) # 输出: True
print(text.startswith("World")) # 输出: False
str.endswith(suffix[, start[, end]])
判断字符串是否以指定的后缀 suffix结束。
text = "Hello, World!"
print(text.endswith("World!")) # 输出: True
print(text.endswith("Hello")) # 输出: False
str.count(sub[, start[, end]])
统计子字符串sub在字符串中出现的次数。
text = "Hello, World! Hello!"
print(text.count("Hello")) # 输出: 2
字符串分割与连接方法
strt.split(sep=None, maxsplit=-1)
将字符串按照指定的分隔符 sep分割成列表,maxsplit指定最大分割次数(默认参数是-1)。
text = "apple,banana,cherry"
a = text.split(",")
print(a) # 输出: ['apple', 'banana', 'cherry']
a = text.split(",", 1)
print(a) # 输出: ['apple', 'banana,cherry']
str.rsplit(sep=None, maxsplit=-1)
从右侧开始分割字符串,功能类似split()。
text = "apple,banana,cherry"
print(text.rsplit(",", 1)) # 输出: ['apple,banana', 'cherry']
str.splitlines([keepends])
按照换行符分割字符串,返回包含各行的列表。keepends为True时,保留换行符。
text = "Hello\nWorld\nPython"
print(text.splitlines()) # 输出: ['Hello', 'World', 'Python']
print(text.splitlines(keepends=True)) # 输出: ['Hello\n', 'World\n', 'Python']
str.join(iterable)
将可迭代对象中的字符串连接为一个新的字符串,使用当前字符串作为分隔符。
fruits = ['apple', 'banana', 'cherry']
print(", ".join(fruits)) # 输出: apple, banana, cherry
字符串修剪与填充方法
str.strip([chars])
去除字符串两端的指定字符(默认去除空白字符)。
text = " Hello, World! \n"
print(text.strip()) # 输出: "Hello, World!"
str.lstrip([chars])
去除字符串左侧的指定字符(默认去除空白字符)。
text = " Hello, World! \n"
print(text.lstrip()) # 输出: "Hello, World! \n"
str.rstrip([]chars)
去除字符串右侧的指定字符(默认去除空白字符)。
text = " Hello, World! \n"
print(text.rstrip()) # 输出: " Hello, World!"
str.center(width[, fillchar])
将字符串居中,并使用fillchar填充两侧(只能是单个字符),使总长度为width。
text = "Hello"
print(text.center(10, '*')) # 输出: **Hello***
str.ljust(width[, fillchar])
将字符串左对齐,并使用fillchar填充右侧(只能是单个字符),使总长度为width。
text = "Hello"
print(text.ljust(10, '-')) # 输出: Hello-----
str.rjust(width[, fillchar])
将字符串右对齐,并使用fillchar填充左侧(只能是单个字符),使总长度为width。
text = "Hello"
print(text.rjust(10, '-')) # 输出: -----Hello
str.zfill(width)
在字符串左侧填充零,使总长度为width。
number = "42"
print(number.zfill(5)) # 输出: 00042
字符串检查方法
str.isalpha()
检查字符串是否只包含字母。
text = "Hello"
print(text.isalpha()) # 输出: True
text = "Hello123"
print(text.isalpha()) # 输出: False
str.isdigit()
检查字符串是否只包含数字。
text = "12345"
print(text.isdigit()) # 输出: Truetext = "123a5"
print(text.isdigit()) # 输出: False
str.isalnum
检查字符串是否只包含字母和数字。
text = "Hello123"
print(text.isalnum()) # 输出: Truetext = "Hello 123"
print(text.isalnum()) # 输出: False
str.islower()
检查字符串中的所有字母是否都是小写。
text = "hell 234db\nbbo"
print(text.islower()) # 输出: Truetext = "hell 234db\nBbo"
print(text.islower()) # 输出: False
str.upper()
检查字符串中的所有字母是否都是大写。
text = "HELLO"
print(text.isupper()) # 输出: Truetext = "Hello"
print(text.isupper()) # 输出: False
str.isspace()
检查字符串是否只包含空白字符(如空格、换行符、制表符等)。
text = " \t\n"
print(text.isspace()) # 输出: Truetext = " Hello "
print(text.isspace()) # 输出: False
str.isnumeric()
检查字符串是否只包含数值字符(包括数字、分数、上标等)。
text = "12345"
print(text.isnumeric()) # 输出: Truetext = "123.45"
print(text.isnumeric()) # 输出: False
str.isidentifier()
检查字符串是否是合法的Python 标识符。
text = "variable_name"
print(text.isidentifier()) # 输出: Truetext = "123variable"
print(text.isidentifier()) # 输出: False
字符串转换方法
str.isascii()
检查字符串是否只包含ASCII字符。
text = "Hello"
print(text.isascii()) # 输出: Truetext = "Hello, 世界"
print(text.isascii()) # 输出: False
str.isdecimal()
检查字符串是否只包含十进制字符。
text = "12345"
print(text.isdecimal()) # 输出: Truetext = "123a5"
print(text.isdecimal()) # 输出: False
str.isprineable()
检查字符串中的所有字符是否都可打印(不包括控制字符)。
text = "Hello, World!"
print(text.isprintable()) # 输出: Truetext = "Hello\nWorld"
print(text.isprintable()) # 输出: False
str.format(*args, **kwargs)
格式化字符串,使用花括号{}作为占位符。
name = "Alice"
age = 99
print("My name is {} and I am {} years old.".format(name, age))
# 输出: My name is Alice and I am 30 years old.
f-字符串(Python 3.6+)
使用f前缀和花括号{}包含变量进行格式化。
name = "Bob"
age = 25
print(f"My name is {name} and I am {age} years old.")
# 输出: My name is Bob and I am 25 years old.
str.format_map(mapping)
使用字典或映射对象进行格式化。
data = {'name': 'Charlie', 'age': 28}
print("My name is {name} and I am {age} years old.".format_map(data))
# 输出: My name is Charlie and I am 28 years old.
感谢浏览,一起学习!
