python 文本序列类型 str

字符串定义

在 Python 中处理文本数据是使用 str 对象,也称为 字符串。 字符串是由 Unicode 码位构成的不可变 序列。

字符串创建方式

单引号:'Hello, World!'
双引号:"Hello, World!"(允许字符串中包含单引号,如 "Don't")
三引号:可以使用三个单引号('''...''')或三个双引号("""...""")创建多行字符串。
# 单引号
single_quote_str = 'Hello, Python!'

# 双引号
double_quote_str = "Hello, Python!"

# 包含单引号的字符串
quote_in_str = "Don't worry about apostrophes"
print(quote_in_str)

# 三引号字符串,可跨多行
multi_line_str = """This is a string that spans
multiple lines in the code."""
print(multi_line_str)

字符串元素访问

通过索引访问

Python字符串支持索引操作,可以通过在方括号[]内指定索引来访问字符串中的单个字符。索引从0开始,所以第一个字符的索引是0,第二个字符的索引是1,以此类推。
text = "Python"
# 访问第一个字符
first_char = text[0]
print(first_char)  # 输出: P

# 访问最后一个字符
last_char = text[-1]
print(last_char)  # 输出: n

通过切片访问

切片操作允许访问字符串中的一部分(子字符串)。切片通过在[]中使用冒号:分隔的两个索引来定义,格式为[start:stop:step],其中start是切片开始的索引,stop是切片结束的索引但不包括此索引,step是步长。
text = "Hello, World!"
# 从索引2到索引5的字符
sub_text = text[2:6]
print(sub_text)  # 输出: llo,

# 从开始到索引5
sub_text2 = text[:6]
print(sub_text2)  # 输出: Hello,

# 从索引7到结束
sub_text3 = text[7:]
print(sub_text3)  # 输出: World!

# 每隔一个字符取一个字符
sub_text4 = text[::2]
print(sub_text4)  # 输出: Hlo ol!

循环访问

text = "Hello, World!"

for i in text:
    print(type(i))
    print(i)
    
# 输出:
<class 'str'>
H
<class 'str'>
e
<class 'str'>
l
<class 'str'>
l
<class 'str'>
o
<class 'str'>
,
<class 'str'>
           # 空格
<class 'str'>
W
<class 'str'>
o
<class 'str'>
r
<class 'str'>
l
<class 'str'>
d
<class 'str'>
!

字符串元素查询

find() 

描述:find() 方法搜索子字符串第一次出现的位置,并返回其索引。如果子字符串不存在,则返回 -1。
用法示例:str.find(sub[, start[, end]])。 在指定的区间[start, end),从左至右,查找子串sub。找到返回索引,没找到返回-1
时间复杂度: 平均情况下为 O(n),其中 n 是字符串的长度。
s = "hello world"
print(s.find("world"))  # 输出: 6
print(s.find("python")) # 输出: -1

rfind()

描述:rfind() 方法搜索子字符串最后一次出现的位置,并返回其索引。如果子字符串不存在,则返回 -1。它从字符串的末尾开始查找。
用法示例:str.rfind(sub[, start[, end]])。在指定的区间[start, end),从右至左,查找子串sub。找到返回索引,没找到返回-1
时间复杂度: 平均情况下为 O(n),其中 n 是字符串的长度。
s = "hello world world"
print(s.rfind("world"))  # 输出: 12

index() 

描述:index() 方法搜索子字符串第一次出现的位置,并返回其索引。但如果找不到子字符串,它会引发一个 ValueError。
用法示例:str.index(sub[, start[, end]])。在指定的区间[start, end),从左至右,查找子串sub。找到返回索引,没找到抛出异常ValueError
时间复杂度: 平均情况下为 O(n),其中 n 是字符串的长度。
str = "hello world"
index = str.index("world")
print(index)  # 输出: 6

# 未找到,抛出 ValueError
try:
    index = str.index("python")
except ValueError:
    print("子字符串未找到")

rindex()  

描述:rindex() 方法搜索子字符串最后一次出现的位置,并返回其索引。但如果找不到子字符串,它会引发一个 ValueError。
用法示例:str.rindex(sub[, start[, end]])。在指定的区间[start, end),从左至右,查找子串sub。找到返回索引,没找到抛出异常ValueError
时间复杂度: 平均情况下为 O(n),其中 n 是字符串的长度。
s = "hello world world"
print(s.rindex("world"))  # 输出: 12

in 操作符

描述:该操作符用于检查子字符串是否存在于另一个字符串中。它返回一个布尔值。
用法示例:sub in str。
时间复杂度: 平均情况下为 O(n),其中 n 是字符串的长度。
s = "hello world"
print("world" in s)  # 输出: True
print("python" in s) # 输出: False

len()

描述:len() 方法用于返回字符串的长度,即字符串中字符的个数。这个方法通常不涉及遍历整个字符串,而是直接返回保存的长度信息,因此执行速度很快。
用法: len(string)。
时间复杂度:  O(1),表示不管字符串有多长,获取字符串长度所需的时间都是固定的,与字符串长度无关。
str = "hello world"
length = len(str)
print(length)  # 输出: 11

count()

描述:count() 方法用于统计字符串中某个子字符串出现的次数。
用法:count(sub[, start[, end]]) 。在指定的区间[start, end),从左至右,统计子串sub出现的次数
时间复杂度:在最坏情况下,时间复杂度为 O(n),其中 n 是字符串长度。因为在最坏情况下,需要遍历整个字符串来计数。
s = "hello hello world"
print(s.count("hello"))  # 输出: 2
print(s.count("world"))  # 输出: 1
print(s.count("l"))      # 输出: 5

字符串连接

join()

描述:join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
用法:"string".join(iterable)。将可迭代对象连接起来,使用string作为分隔符。可迭代对象本身元素都是字符串。返回一个新字符串。
时间复杂度:join() 方法的时间复杂度是 O(n)。
 join() 方法是一个更高效的字符串连接方式,尤其适用于连接大量字符串。它将字符串序列作为参数,并在每个字符串之间插入指定的分隔符。
str_list = ["Hello", "World", "Python"]
result = " ".join(str_list)
print(result)  # 输出:Hello World Python

使用加号 +

描述:+ 操作符可以将两个字符串连接成一个新字符串。
用法:+ -> str。返回一个新字符串。
时间复杂度:如果有 n 个字符串需要连接,时间复杂度为 O(n)。
这种方法是最直接的字符串连接方式,可以通过简单地将多个字符串用加号连接起来来实现。这种方法适用于连接少量的字符串,但在连接大量字符串时可能会导致性能下降。
str1 = "Hello"
str2 = " World"
result = str1 + str2
print(result)  # 输出:Hello World

字符串分割

split()

说明:str.split() 是 Python 字符串对象的一个方法,用于根据指定的分隔符将字符串拆分为子字符串,并返回包含拆分后子字符串的列表。
语法:str.split(sep=None, maxsplit=-1)。从左至右。
        sep: 指定的分隔符,如果不提供分隔符,则默认会根据空白字符(空格、制表符、换行符等)进行分割。
        maxsplit: 可选参数,指定最大的分割次数。默认值为 -1,表示没有限制。
# 使用默认空白字符分隔字符串
text = "Hello World"
result = text.split()
print(result)   # 输出: ['Hello', 'World']

# 使用逗号分隔字符串,限制分割次数为1
text = "apple,banana,cherry,orange"
result = text.split(",", 1)
print(result)   # 输出: ['apple', 'banana,cherry,orange']

# 使用换行符 '\n' 分隔多行文本
text = "apple\nbanana\ncherry\norange"
result = text.split("\n")
print(result)   # 输出: ['apple', 'banana', 'cherry', 'orange']

# 使用多个不同分隔符进行分割
import re

text = "Hello! I-just!want@to^split,this"
result = re.split(r'[!-@^, ]+', text)
print(result)   # 输出: ['Hello', ' I', 'just', 'want', 'to', 'split', 'this']

rsplit()

说明:str.rsplit() 方法用于从字符串末尾开始按指定的分隔符将字符串进行分割,返回分割后的子字符串列表。
语法:str.rsplit(sep=None, maxsplit=-1)。从右向左
        sep:可选,指定分隔符,默认为 None(使用空白字符分割)。
        maxsplit:可选,最大分割次数,默认为 -1(无限制分割)。
# 使用默认的空白字符分割
phrase = "one two three four"
words = phrase.rsplit()
print(words)  # 输出: ['one', 'two', 'three', 'four']

# 使用自定义分隔符进行分割
data = "apple,banana,grape,orange"
fruits = data.rsplit(",", 2)  # 使用逗号作为分隔符,最多分割2次
print(fruits)  # 输出: ['apple,banana', 'grape', 'orange']

# 处理换行分隔的多行文本
multiline_text = "line1\nline2\nline3"
lines = multiline_text.rsplit("\n")  # 使用换行符分割
print(lines)    # 输出: ['line1', 'line2', 'line3']

splitlines()

说明:str.splitlines() 方法按照换行符(\n, \r, 或 \r\n)分割字符串,并返回包含各行作为元素的列表。
语法:str.splitlines(keepends=False)
        keepends: 可选参数,默认为 False,若设为 True 则会保留每行末尾的换行符。
# 拆分简单的多行字符串
text = "apple\nbanana\ncherry\norange"
result = text.splitlines()
print(result)  # 输出: ['apple', 'banana', 'cherry', 'orange']

# 保留行末尾的换行符
text = "apple\nbanana\ncherry\norange"
result = text.splitlines(keepends=True)
print(result)  # 输出: ['apple\n', 'banana\n', 'cherry\n', 'orange']

# 处理包含空行的多行文本
text = "apple\nbanana\n\ncherry\norange\n"
result = text.splitlines()
print(result)  # 输出: ['apple', 'banana', '', 'cherry', 'orange']

# 使用不同换行符进行拆分
text = "apple\rbanana\rcherry\rorange"
result = text.splitlines()
print(result)  # 输出: ['apple', 'banana', 'cherry', 'orange']

partition(sep)

说明:根据指定的分隔符 sep 将字符串拆分为三部分,并返回一个元组,其中包含拆分结果。
语法:str.partition(sep)。 从左至右。sep: 指定的分隔符,用于拆分字符串。
返回值:返回一个元组,包含拆分后的三部分:分隔符左侧的部分、分隔符本身和分隔符右侧的部分。
# 拆分简单的字符串
text = "apple,banana,cherry,orange"
result = text.partition(",")
print(result)  # 输出: ('apple', ',', 'banana,cherry,orange')

# 处理不存在分隔符的情况
text = "apple"
result = text.partition(",")
print(result)  # 输出: ('apple', '', '')

# 拆分多个不同分隔符的字符串
text = "apple,banana;cherry orange"
result = text.partition(";")
print(result)  # 输出: ('apple,banana', ';', 'cherry orange')

# 拆分多行文本
text = "apple\nbanana\ncherry\norange"
result = text.partition("\n")
print(result)  # 输出: ('apple', '\n', 'banana\ncherry\norange')

字符串大小写

upper()

描述:str.upper() 方法将字符串中的所有小写字母转换为大写字母,并返回修改后的新字符串,原始字符串本身不会发生改变。
适用场景:通常用于用户输入的规范化处理,确保不论用户如何输入,程序都能以统一的格式处理文本。例如,在不区分大小写的用户名或电子邮件地址匹配中使用。
# 将字符串中的小写字母转换为大写字母
text = "Hello, World!"
uppercase_text = text.upper()
print(uppercase_text)  # 输出: "HELLO, WORLD!"

# 处理含有数字和特殊字符的字符串
mixed_text = "abc123!@#"
uppercase_mixed_text = mixed_text.upper()
print(uppercase_mixed_text)  # 输出: "ABC123!@#"

# 与变量一起使用
name = "Alice"
greeting = "Hello, " + name.upper() + "!"
print(greeting)  # 输出: "Hello, ALICE!"

# 对不支持大小写转换的特殊字符
text = "∂ is a symbol"
uppercase_text = text.upper()
print(uppercase_text)  # 输出: "∂ IS A SYMBOL" (特殊字符∂不会变成大写形式)

lower()

描述:str.lower() 方法将字符串中的所有大写字母转换为小写字母,并返回修改后的新字符串,原始字符串本身不会被改变。
适用场景:通常用于用户输入的规范化处理,确保不论用户如何输入,程序都能以统一的格式处理文本。例如,在不区分大小写的用户名或电子邮件地址匹配中使用。
# 将字符串中的大写字母转换为小写字母
text = "Hello, World!"
lowercase_text = text.lower()
print(lowercase_text)  # 输出: "hello, world!"

# 处理包含数字和特殊字符的字符串
mixed_text = "ABC123!@#"
lowercase_mixed_text = mixed_text.lower()
print(lowercase_mixed_text)  # 输出: "abc123!@#"

# 与变量一起使用
name = "Alice"
greeting = "Hello, " + name.lower() + "!"
print(greeting)  # 输出: "Hello, alice!"

# 对不支持大小写转换的特殊字符
text = "∂ is a symbol"
lowercase_text = text.lower()
print(lowercase_text)  # 输出: "∂ is a symbol" (特殊字符∆不会被转换为小写形式)

swapcase() 

描述:string.swapcase() 将字符串中的小写字母转换为大写字母,大写字母转换为小写字母。
适用场景:在某些特殊情境下使用,如创建特殊的文本效果或处理特定编码的文本。
text = "Hello, World!"
swapped_text = text.swapcase()
print(swapped_text)  # 输出 "hELLO, wORLD!"

casefold()

描述:string.casefold()用于将字符串中的字符转换为小写并处理 Unicode。这个方法类似于 lower() 方法,但针对 Unicode 字符串有一些额外的处理,可以更好地支持一些特殊字符的大小写转换。
适用场景:
  不区分语言环境的字符串比较:当你需要比较来自多种语言的字符串时,casefold() 提供了一种更加均一和彻底的方式来处理字符的大小写,使得比较操作更加准确。
  数据清洗和预处理:在文本数据预处理时,casefold() 可以帮助去除文本的大小写差异,尤其是在处理包含特殊字符的文本时,确保数据的一致性。
  不区分大小写的搜索和匹配:在实现不区分大小写的搜索功能时,使用 casefold() 可以更准确地匹配目标字符串,即使目标字符串包含特殊字符或属于非英语语言。
# 示例 1: 基本用法
text = "Python Programming"
print(text.casefold())  # 输出: python programming

# 示例 2: 与 lower() 的区别
text_german = "Straße"  # 德语中的 'ß' 相当于双 's'
print(text_german.lower())  # 输出: straße
print(text_german.casefold())  # 输出: strasse

# 示例 3: 多语言环境下的字符串比较
# 土耳其语中的 'I' 在转换为小写时变成 'ı'(不带点的 i)
turkish = "Istanbul"
english = "istanbul"

print(turkish.lower() == english.lower())  # False
print(turkish.casefold() == english.casefold())  # True

# 示例 4: 使用 casefold() 进行不区分大小写的搜索
def case_insensitive_search(needle, haystack):
    return needle.casefold() in haystack.casefold()

text = "CaseFolding Example"
search_word = "example"

print(case_insensitive_search(search_word, text))  # 输出: True

字符串排版

capitalize()

描述:string.capitalize() 用于将字符串的第一个字符转换为大写,而将剩余字符转换为小写。
适用场景:适用于需要按照一定的文本格式输出的场合,如将人名、标题等格式化为首字母大写。
text = "hello, world!"
capitalized_text = text.capitalize()
print(capitalized_text) # 输出 "Hello, world!"

title() 

描述:string.title() 用于将字符串中每个单词的第一个字母转换为大写,而其他字母转换为小写。
适用场景:适用于需要按照一定的文本格式输出的场合,如将人名、标题等格式化为首字母大写。
text = "hello, world!"
title_text = text.title()
print(title_text) # 输出 "Hello, World!"

center()

描述:用于将原字符串居中对齐,并使用指定的字符(默认为空格)填充至指定的宽度。这个方法非常适合在打印输出或制作文本界面时,需要美化或格式化字符串显示的场景。
语法:str.center(width[, fillchar])
参数:
  width: 整数,指定了返回字符串的总宽度。
  fillchar (可选): 指定填充字符,默认为空格。这必须是长度为 1 的字符串。
返回值:返回一个新的字符串,它是原字符串在指定宽度中居中对齐后的结果,两边用 fillchar 填充至总长度达到 width。如果原字符串的长度大于或等于 width,则返回原字符串。
适用场景:
    文本美化:在制作文本界面或打印输出报表时,使用 str.center() 可以美化标题或任何需要居中显示的文本。
    格式化输出:在输出数据到控制台或文本文件时,为了提高可读性,可以使用 str.center() 方法将关键信息居中显示。
    创建简单的文本界面:在开发命令行程序时,使用 str.center() 可以帮助创建简洁而美观的文本菜单或界面。
# 示例 1: 基本用法
text = "hello"
centered_text = text.center(20)
print(centered_text)  # 输出: "       hello        "

# 示例 2: 使用自定义填充字符
text = "world"
centered_text = text.center(20, '*')
print(centered_text)  # 输出: "*******world********"

# 示例 3: 当原字符串长度大于width时
text = "Python is awesome"
centered_text = text.center(10)
print(centered_text)  # 输出: "Python is awesome" (原字符串未被截断)

# 示例 4: 结合其他字符串格式化使用
title = "Menu"
items = ["Pizza", "Pasta", "Salad"]
print(title.center(20, "-"))
for item in items:
    print(item.center(20))

'''
输出:
--------Menu---------
       Pizza        
       Pasta        
       Salad        
'''

# 示例 5: 在制作简单文本界面或报表时居中对齐标题
header = "Sales Report"
print(header.center(50, '='))
# 输出: "=================Sales Report=================="

zfill()

描述:用于向字符串的左侧填充零,直到字符串达到指定的宽度。
语法:str.zfill(width)
参数:
    width: 整数,表示结果字符串的最小宽度。如果原始字符串的长度已经等于或超过了这个宽度,那么原字符串将会被返回,不会添加额外的零。
返回值:返回一个新字符串,长度至少为 width 指定的宽度,如果原始字符串长度小于 width,则在左侧用零填充直到长度为 width。
适用场景:
    数字字符串格式化:当你需要确保所有数字字符串具有相同的长度时,str.zfill() 可以确保数字左侧用零填充到相应长度,非常适合于文件命名、报表生成等需要统一格式的数字字符串。
    时间数据格式化:在处理时间时,比如将小时或分钟转换为字符串表示,可能需要确保这些字符串具有双位数字格式,str.zfill() 方法可以用来实现这一点。
    财务报告:在生成财务报告或数据表格时,str.zfill() 可以帮助对齐货币数额或其他数值,提高报告的可读性和专业度。
# 示例 1: 基本用法
number_str = "50"
filled_str = number_str.zfill(5)
print(filled_str)  # 输出: "00050"

# 示例 2: 对带有符号的数字字符串填充
negative_number_str = "-50"
filled_str = negative_number_str.zfill(5)
print(filled_str)  # 输出: "-0050"

# 示例 3: 对于已经足够长的字符串不进行填充
long_str = "Python"
filled_str = long_str.zfill(3)
print(filled_str)  # 输出: "Python"

# 示例 4: 在格式化时间时使用
time_str = "9:15"
filled_time_str = time_str.zfill(5)
print(filled_time_str)  # 输出: "09:15"

# 示例 5: 用于生成格式化的文档或票号等
doc_number = "123"
formatted_doc_number = doc_number.zfill(10)
print(formatted_doc_number)  # 输出: "0000000123"

ljust()

描述:用于将字符串向左对齐,并使用指定的字符(默认为空格)填充至指定的宽度。
语法:str.ljust(width[, fillchar])
参数:
    width: 整数,指定返回字符串的总宽度。
    fillchar (可选): 指定用于填充的字符,默认为空格。这必须是长度为 1 的字符串。
返回值:返回一个新的字符串,它是原字符串在指定宽度中左对齐后的结果,右边用 fillchar 填充至总长度达到 width。如果原字符串的长度大于或等于 width,则返回原字符串。
适用场景:
    文本美化和格式化:在输出文本到控制台或文件时,str.ljust() 可以用来美化和格式化输出,确保文本的整齐和可读性。
    制作文本表格或报表:在制作文本形式的表格或报表时,str.ljust() 能够帮助你左对齐列数据,使得整个表格的布局更加整洁。
    对齐日志和消息输出:在打印日志或消息时,使用 str.ljust() 对不同部分进行左对齐,可以提高日志信息的可读性。
# 示例 1: 基本用法
text = "Python"
left_justified_text = text.ljust(10)
print(f"'{left_justified_text}'")  # 输出: 'Python    '

# 示例 2: 使用自定义填充字符
text = "Python"
left_justified_text = text.ljust(10, '*')
print(f"'{left_justified_text}'")  # 输出: 'Python****'

# 示例 3: 当原字符串长度大于width时
text = "Python Programming"
left_justified_text = text.ljust(10)
print(f"'{left_justified_text}'")  # 输出: 'Python Programming' (原字符串未被截断)

# 示例 4: 格式化输出多列数据
names = ["Alice", "Bob", "Charlie"]
ages = [24, 30, 18]

for name, age in zip(names, ages):
    print(name.ljust(10) + str(age).ljust(3))

'''
输出:
Alice     24 
Bob       30 
Charlie   18 
'''

# 示例 5: 在制作简单文本报表时左对齐标题
headers = ["Name", "Age", "Occupation"]
print(" | ".join(header.ljust(10) for header in headers))
# 输出:Name       | Age        | Occupation

rjust()

描述:用于将字符串向右对齐,并使用指定的字符(默认为空格)填充至指定的宽度。
语法:str.rjust(width[, fillchar])
参数:
    width: 整数,指定返回字符串的总宽度。
    fillchar (可选): 指定用于填充的字符,默认为空格。这必须是长度为 1 的字符串。
返回值:返回一个新的字符串,它是原字符串在指定宽度中右对齐后的结果,左边用 fillchar 填充至总长度达到 width。如果原字符串的长度大于或等于 width,则返回原字符串。
适用场景:
    数据和报表格式化:当需要创建文本形式的数据报表时,`str.rjust()` 可以使列数据右对齐,提高报表的可读性和专业度。
    数字输出对齐:在输出数字列表或表格时,使用 `str.rjust()` 保持数字右对齐,特别是在处理含有不同位数的数字时,能够提供一致且清晰的视觉效果。
    文本美化:在制作文本界面或输出日志信息时,`str.rjust()` 有助于保持文本的整齐和对齐,增强文本输出的美观度和可读性。
# 示例 1: 基本用法
text = "Python"
right_justified_text = text.rjust(10)
print(f"'{right_justified_text}'")  # 输出: '    Python'

# 示例 2: 使用自定义填充字符
text = "Python"
right_justified_text = text.rjust(10, '*')
print(f"'{right_justified_text}'")  # 输出: '****Python'

# 示例 3: 当原字符串长度大于width时
text = "Python Programming"
right_justified_text = text.rjust(10)
print(f"'{right_justified_text}'")  # 输出: 'Python Programming' (原字符串未被截断)

# 示例 4: 格式化输出数字,使其右对齐
numbers = [5, 50, 500, 5000]
for number in numbers:
    print(str(number).rjust(5))

'''
输出:
    5
   50
  500
 5000
'''

# 示例 5: 在制作文本报表时右对齐列数据
headers = ["Name", "Age", "Salary"]
rows = [
    ["Alice", "29", "3500"],
    ["Bob", "24", "2400"],
    ["Charlie", "35", "5000"]
]

print(" | ".join(header.rjust(10) for header in headers))
for row in rows:
    print(" | ".join(cell.rjust(10) for cell in row))

'''
输出:
      Name |        Age |     Salary
     Alice |         29 |       3500
       Bob |         24 |       2400
   Charlie |         35 |       5000
'''

字符串修改

str 类型是不可变的,这意味着一旦创建了一个字符串,便不能修改它的内容。但是,可以通过创建新的字符串来实现对原字符串的各种修改。

replace()

描述:用于替换字符串中的子串。
语法:str.replace(old, new[, count])
    old: 要被替换的旧子串。
    new: 新子串,用来替换旧子串。
    count (可选): 指定替换的最大次数。如果不指定,将替换所有找到的旧子串。
返回值:返回一个新的字符串,其中所有的 old 都被 new 替换。
适用场景:用于文本数据的清洗或修改。
# 简单替换
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text)  # 输出 "Hello, Python!"

# 替换多次出现的子字符串
text = "one two one two one"
new_text = text.replace("one", "three")  # 替换所有出现的 "one"
print(new_text)  # 输出 "three two three two three"

# 指定替换次数
text = "one two one two one"
new_text = text.replace("one", "three", 2)  # 仅替换前两次出现的 "one"
print(new_text)  # 输出 "three two three two one"

# 替换为空字符串
text = "Hello, World!"
new_text = text.replace("o", "")
print(new_text)  # 输出 "Hell, Wrld!"

# 大小写敏感替换
text = "Apple and apple are fruits."
new_text = text.replace("apple", "orange")  # 区分大小写
print(new_text)  # 输出 "Apple and orange are fruits."

strip()

描述:用于去除字符串首尾的空白符(包括空格、换行符、制表符等)。
语法:string.strip(characters)。 chars (可选): 指定要从字符串首尾去除的字符集。如果不指定或为 None,则默认去除空白字符。
返回值:返回一个新的字符串,其中开头和结尾的指定字符都被删除。
适用场景:用于处理从文件或网络中读取的数据,去除多余的空白或特定字符。
lstrip([chars]) -> str  # 从左开始
rstrip([chars]) -> str  # 从有开始
# 删除默认空格
text = "   Hello, World!   "
new_text = text.strip()
print(new_text)  # 输出 "Hello, World!"

# 删除指定字符
text = "----Hello, World!----"
new_text = text.strip("-")
print(new_text)  # 输出 "Hello, World!"

# 删除多个指定字符
text = "**!---Hello, World!---**"
new_text = text.strip("*!-")
print(new_text)  # 输出 "Hello, World"

# 删除换行符和制表符
text = "\n\tHello, World!\n\t"
new_text = text.strip("\n\t")
print(new_text)  # 输出 "Hello, World!"

字符串判断

startswith()

用途:startswith() 方法用于检查字符串是否以指定的子字符串开头。
语法:string.startswith(prefix, start, end)
    prefix:要检查的前缀,可以是一个字符串或包含多个字符串的元组。
    start(可选):指定搜索的起始位置。
    end(可选):指定搜索的结束位置。
返回值:如果字符串以指定的前缀开头,则返回 True;否则返回 False。
适用场景:方法在编写需要验证字符串格式的程序时非常实用,比如在处理文件名或路由路径时验证它们的格式。
# 简单的前缀检查
print("hello world".startswith("hello"))  # 输出: True

# 使用元组检查多个可能的前缀
print("hello world".startswith(("hi", "hello", "hey")))  # 输出: True

# 指定开始和结束位置
print("hello world".startswith("world", 6))  # 输出: True

# 前缀不匹配
print("hello world".startswith("world"))  # 输出: False

# 检查空字符串前缀
print("hello world".startswith(""))  # 输出: True

# 完全匹配
print("hello".startswith("hello"))  # 输出: True

# 使用结束位置限制
print("hello world".startswith("hello", 0, 5))  # 输出: True

# 前缀是完整字符串
print("hello".startswith("hello world"))  # 输出: False

endswith()

用途:endswith() 方法用于检查字符串是否以指定的子字符串结尾。
语法:string.endswith(suffix, start, end)
    suffix:要检查的后缀,可以是一个字符串或包含多个字符串的元组。
    start(可选):指定搜索的起始位置。
    end(可选):指定搜索的结束位置。
返回值:如果字符串以指定的后缀结尾,则返回 True;否则返回 False。
适用场景:适合用于验证文件扩展名、URL路径结束部分或任何需要确认字符串结尾特定格式的场合。
# 简单的后缀检查
print("example.txt".endswith(".txt"))  # 输出: True

# 使用元组检查多个可能的后缀
print("photo.jpg".endswith((".png", ".jpg", ".jpeg")))  # 输出: True

# 指定开始和结束位置
print("example.txt".endswith("ample", 2, 7))  # 输出: True

# 后缀不匹配
print("example.txt".endswith(".doc"))  # 输出: False

# 检查空字符串后缀
print("hello world".endswith(""))  # 输出: True

# 完全匹配
print("hello".endswith("hello"))  # 输出: True

# 使用开始位置限制
print("example.txt".endswith("example", 0, 7))  # 输出: True

# 后缀是完整字符串
print("hello".endswith("hello world"))  # 输出: False

isalnum() 

用途: isalnum() 方法用于检查字符串是否只包含字母和数字字符。
语法: string.isalnum()
返回值: 如果字符串中所有的字符都是字母和数字,则返回 True;否则返回 False。
适用场景:适用于验证用户输入的数据格式,比如用户名、密码等,其中不允许有特殊字符或空格。
# 全是字母数字字符
print("abc123".isalnum())  # 输出: True

# 包含空格
print("abc 123".isalnum())  # 输出: False

# 全是字母
print("abcdef".isalnum())  # 输出: True

# 全是数字
print("123456".isalnum())  # 输出: True

# 包含特殊字符
print("abc#123".isalnum())  # 输出: False

# 空字符串
print("".isalnum())  # 输出: False

# 包含下划线(注意下划线也被视为特殊字符)
print("abc_123".isalnum())  # 输出: False

# 混合字母数字和标点
print("123,abc".isalnum())  # 输出: False

isalpha() 

用途: isalpha() 方法用于检查字符串是否只包含字母字符。
语法: string.isalpha()
返回值: 如果字符串中所有的字符都是字母,则返回 True;否则返回 False。
适用场景:适用于验证文本输入(如只接受字母的姓名输入)和处理语言数据。该方法在国际化应用中尤其有用,因为它支持 Unicode 字母字符,能够识别各种语言中的字母。
# 全是字母
print("Hello".isalpha())  # 输出: True

# 包含空格
print("Hello world".isalpha())  # 输出: False

# 空字符串
print("".isalpha())  # 输出: False

# 包含数字
print("Hello123".isalpha())  # 输出: False

# 全是大写字母
print("HELLO".isalpha())  # 输出: True

# 全是小写字母
print("hello".isalpha())  # 输出: True

# 包含特殊字符
print("Hello!".isalpha())  # 输出: False

# 非英文字母(例如其他语言的字母)
print("Привет".isalpha())  # 输出: True

# 包含下划线
print("Hello_World".isalpha())  # 输出: False

isdecimal()

用途: isdecimal() 方法用于检查字符串是否只包含十进制数字字符(0-9)。
语法: string.isdecimal()
返回值: 如果字符串中所有的字符都是十进制数字,则返回 True;否则返回 False。
适用场景:验证数字输入时非常有用,例如验证用户输入的年龄、数量等。该方法也可以识别其他文化中使用的数字,如阿拉伯和全角数字,但不包括罗马数字等非标准十进制形式。
# 全是十进制数字
print("12345".isdecimal())  # 输出: True

# 包含字母
print("12345a".isdecimal())  # 输出: False

# 空字符串
print("".isdecimal())  # 输出: False

# 包含空格
print("123 45".isdecimal())  # 输出: False

# 包含特殊字符
print("123#45".isdecimal())  # 输出: False

# 包含小数点
print("123.45".isdecimal())  # 输出: False

# 包含非拉丁数字
print("١٢٣".isdecimal())  # 输出: True  # 这些是阿拉伯数字

# 包含全角数字
print("1234".isdecimal())  # 输出: True  # 这些是中文全角数字

# 罗马数字
print("Ⅴ".isdecimal())  # 输出: False  # 罗马数字不被视为十进制数字

isdigit()

用途: isdigit() 方法用于检查字符串是否只包含数字字符(0-9)。
语法: string.isdigit()
返回值: 如果字符串中所有的字符都是数字,则返回 True;否则返回 False。
适用场景:用来检查字符串是否只包含数字字符,这在验证数字输入时非常有用,尤其是在需要区分不同类型数字字符的场合,如罗马数字或全角数字。与 isdecimal() 不同,isdigit() 能识别更广泛的数字类型,包括一些特殊的数字字符。
# 全是数字
print("12345".isdigit())  # 输出: True

# 包含字母
print("12345a".isdigit())  # 输出: False

# 空字符串
print("".isdigit())  # 输出: False

# 包含空格
print("123 45".isdigit())  # 输出: False

# 包含特殊字符
print("123#45".isdigit())  # 输出: False

# 包含小数点
print("123.45".isdigit())  # 输出: False

# 罗马数字
print("Ⅴ".isdigit())  # 输出: True  # 罗马数字视为数字字符

# 包含全角数字
print("1234".isdigit())  # 输出: True  # 全角数字视为数字字符

# 包含超级脚本数字
print("²".isdigit())  # 输出: True  # 超级脚本数字也被认为是数字字符

isidentifier()

用途: isidentifier() 必须以字母(A-Z 或 a-z)或下划线(_)开头,除首字符外,其余字符可以是字母、下划线或数字(0-9)。
语法: string.isidentifier()
返回值: 如果字符串是一个合法的 Python 标识符,则返回 True;否则返回 False。
适用场景:用于检查字符串是否是一个合法的 Python 标识符(即变量名)。
# 有效的标识符
print("var1".isidentifier())  # 输出: True

# 以数字开头,无效
print("1var".isidentifier())  # 输出: False

# 包含特殊字符,无效
print("var$".isidentifier())  # 输出: False

# 使用下划线,有效
print("_var".isidentifier())  # 输出: True

# 关键字,无效
print("for".isidentifier())  # 输出: True

# 空字符串,无效
print("".isidentifier())  # 输出: False

islower()

用途: islower() 方法用于检查字符串是否至少包含一个字母字符且所有字母字符都是小写字母。
语法: string.islower()
返回值: 如果字符串中至少有一个字母字符且所有字母字符都是小写,则返回 True;否则返回 False。
适用场景:适合用于文本处理、数据清洗或在用户输入验证中判断字符串的格式。
# 全是小写字母
print("hello".islower())  # 输出: True

# 含有大写字母
print("Hello".islower())  # 输出: False

# 没有字母,只有数字
print("12345".islower())  # 输出: False

# 小写字母和数字混合
print("abc123".islower())  # 输出: True

# 全是大写字母
print("HELLO".islower())  # 输出: False

# 空字符串
print("".islower())  # 输出: False

# 小写字母和特殊字符混合
print("hello!".islower())  # 输出: True

# 只包含特殊字符
print("!@#$".islower())  # 输出: False

isupper()

用途: isupper() 方法用于检查字符串是否至少包含一个字母字符且所有字母字符都是大写字母。
语法: string.isupper()
返回值: 如果字符串中至少有一个字母字符且所有字母字符都是大写,则返回 True;否则返回 False。
适用场景:适合在文本处理、数据清洗或在验证用户输入中判断字符串的格式,尤其是在需要强制大写输入的场合。
# 全是大写字母
print("HELLO".isupper())  # 输出: True

# 含有小写字母
print("Hello".isupper())  # 输出: False

# 没有字母,只有数字
print("12345".isupper())  # 输出: False

# 大写字母和数字混合
print("ABC123".isupper())  # 输出: True

# 全是小写字母
print("hello".isupper())  # 输出: False

# 字符串
print("".isupper())  # 输出: False

# 大写字母和特殊字符混合
print("HELLO!".isupper())  # 输出: True

# 只包含特殊字符
print("!@#$".isupper())  # 输出: False

isspace()

用途: isspace() 方法用于检查一个字符串中是否只包含空格字符(包括空格、制表符、换行符等)。
语法: string.isspace()
返回值: 如果字符串中只包含空格字符,则返回 True;否则返回 False。
适用场景:这个方法在处理文本数据,特别是在清洗和准备数据输入或验证用户输入的空格状态时,非常有用。
空格 ' '
制表符 '\t'
换行 '\n'
回车 '\r'
垂直制表符 '\v'
换页 '\f'
# 只包含空格
print("    ".isspace())  # 输出: True

# 包含空格和制表符
print(" \t \n \r".isspace())  # 输出: True

# 包含空格和非空白字符
print(" Hello ".isspace())  # 输出: False

# 只包含换行符
print("\n".isspace())  # 输出: True

# 空字符串
print("".isspace())  # 输出: False

# 包含数字和空格
print("1234 ".isspace())  # 输出: False

# 只包含制表符
print("\t".isspace())  # 输出: True

# 只包含特殊字符,非空白
print("!@#$".isspace())  # 输出: False

字符串格式化

python 提供了几种不同的字符串格式化方法,包括百分号(%)格式化、str.format() 方法,以及较新的 f-string(格式化字符串字面值)方法。

百分号(%)

描述:百分号(%)格式化是一种古老但强大的方式,用于在字符串中插入一个或多个变量。这种格式化方法受到 C 语言中 printf 函数的启发
用法:
    %s - 字符串
    %d 或 %i - 整数
    %f - 浮点数
    %x 或 %X - 十六进制数
缺点:在性能上不如str.format() 方法或 f-string 灵活和强大。
# 基础字符串和整数格式化
name = "Alice"
age = 30
print("Hello, %s. You are %d years old." % (name, age)) # 输出:Hello, Alice. You are 30 years old.

# 浮点数格式化,指定小数点后的位数
height = 175.5
print("Your height is %.1f cm." % height)  # 输出:Your height is 175.5 cm.

# 多种数据类型
order_number = 937
total = 275.75
print("Order # %d: Total amount is $%.2f" % (order_number, total))  # 输出:Order # 937: Total amount is $275.75

# 十六进制格式化
number = 255
print("The number in hexadecimal is %x." % number)  # 输出:The number in hexadecimal is ff.

# 使用字典传递值
data = {"name": "Bob", "age": 25}
print("Hello, %(name)s. You are %(age)d years old." % data)  # 输出:Hello, Bob. You are 25 years old.

# 转义百分号(如果你想打印一个百分号)
percentage = 85
print("You scored %d%% on your test." % percentage)  # 输出:You scored 85% on your test.

# 左填充和右填充
number = 7
print("Left padded with spaces: %5d." % number)  # 总宽度为5,左填充空格。 输出:Left padded with spaces:     7.  
print("Right padded with zeros: %05d." % number)  # 总宽度为5,右填充零。  输出:Right padded with zeros: 00007.

format()

描述:format() 方法是一种对字符串进行格式化的方法,可以替换字符串中的格式化字段 {} 为传入的参数值。
用法:"{}".format(*args, **kwargs)
优点:
    可读性:与 % 格式化相比,str.format() 通常更易于阅读和理解。
    功能性:提供更多控制格式的选项,如数字格式化、填充和对齐。
    灵活性:支持通过索引、关键字和对象属性进行复杂的数据引用。
# 基础使用,没有指定索引,默认按顺序
print("Hello, {}. You are {} years old.".format("Alice", 30))  # 输出:Hello, Alice. You are 30 years old.

# 指定索引
print("Hello, {1}. You are {0} years old.".format(30, "Bob"))  # 输出:Hello, Bob. You are 30 years old.

# 关键字参数
print("Hello, {name}. You are {age} years old.".format(name="Carol", age=25))  # 输出:Hello, Carol. You are 25 years old.

# 填充和对齐文本,指定宽度
print("{:>10}".format("right"))  # 右对齐  # 输出:     right
print("{:10}".format("left"))    # 左对齐  # 输出:left      
print("{:^10}".format("center")) # 居中    # 输出:  center  

# 数字格式化,包括浮点精度和填充
print("The number is: {:+.2f}".format(3.14159))  # 显示符号并保留两位小数  # 输出:The number is: +3.14

# 使用字典进行格式化
data = {'first': 'Hector', 'last': 'Miller'}
print("First Name: {first}, Last Name: {last}".format(**data))  # 输出:First Name: Hector, Last Name: Miller

# 宽度和精度组合,用于浮点数
print("Pi is approximately {0:.3f}.".format(3.14159))  # 输出:Pi is approximately 3.142.

# 使用下划线作为千位分隔符
print("Large number: {0:_}".format(1000000))  # 输出:Large number: 1_000_000

# 二进制、十六进制、八进制格式化
print("Binary: {0:b}, Hex: {0:x}, Octal: {0:o}".format(255))  # 输出:Binary: 11111111, Hex: ff, Octal: 377

# 嵌套字段
coords = (3, 5)
print("X: {0[0]}, Y: {0[1]}".format(coords))  # coords 是一个元组  # 输出:X: 3, Y: 5

# 在字符串中包含大括号
print("{{{{Hello}} {name}}}".format(name="Bob"))  # 输出: {{Hello} Bob}

F-string(推荐用法)

描述:F-string 是 Python 3.6 版本及更高版本中引入的一种方便的字符串格式化方式,可以在字符串前加上 f 或 F 前缀,然后在字符串中使用大括号 {} 包含表达式或变量。
用法:f"{}" 或 F"{}"
优点:
    性能:F-string 在执行时比其他字符串格式化方法(如 % 格式化和 str.format())更快。
    可读性:直接在字符串中嵌入变量和表达式,代码更清晰易读。
    简洁性:不需要额外的方法调用或传递参数,直接书写即可。
# 基础使用
name = "Alice"
age = 30
print(f"Hello, {name}. You are {age} years old.")  # 输出:Hello, Alice. You are 30 years old.

# 算术表达式
a = 5
b = 10
print(f"Five plus ten is {a + b}.")          # 输出:Five plus ten is 15.

# 调用函数
def get_message():
    return "Python is fun"
print(f"The message is: {get_message()}.")   # 输出:The message is: Python is fun.

# 对象属性和方法
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hi, my name is {self.name} and I am {self.age} years old."

alice = Person("Alice", 30)
print(alice.greet())    # 输出:Hi, my name is Alice and I am 30 years old.

# 格式化数字
from math import pi
print(f"Pi rounded to three decimal places is {pi:.3f}.")  # 输出:Pi rounded to three decimal places is 3.142.

# 内联字典和列表访问
d = {'key': 'value'}
lst = [1, 2, 3]
print(f"The value from dictionary is {d['key']} and second list item is {lst[1]}.")  # 输出:The value from dictionary is value and second list item is 2.

# 大括号转义
print(f"Show me the braces: {{ and }}.")  # 输出:Show me the braces: { and }.

# 复杂表达式
x = 10
y = 5
print(f"{x} times {y} is {x * y}, and {x} divided by {y} is {x / y}.")  # 输出:10 times 5 is 50, and 10 divided by 5 is 2.0.

# 多行F-string
name = "Bob"
age = 25
greeting = (
    f"Hello, {name}. "
    f"You are {age} years old. "
    f"Next year, you will be {age + 1}."
)
print(greeting)  # 输出:Hello, Bob. You are 25 years old. Next year, you will be 26.

# 进制
print(f"| {i:>3}  | {i:0>2X}h  | {i:0>3o}   | {char:^5} |")
# i:>3} 表示将 i 的十进制表示右对齐,并确保至少占用3个字符宽度。
# {i:0>2X}h 表示将 i 的十六进制表示为至少两位,不足的前面补0,并在后面添加h表示十六进制。
# {i:0>3o} 表示将 i 的八进制表示为至少三位,不足的前面补0。
# {char:^5} 表示将字符 char 居中对齐,并确保至少占用5个字符宽度。

参考文档

https://docs.python.org/zh-cn/3.12/library/stdtypes.html#/text-sequence-type-str

posted @ 2024-04-18 10:42  小吉猫  阅读(8)  评论(0编辑  收藏  举报