Files
2026-05-06 11:21:42 +08:00

249 lines
9.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 字符串
str1 = "字符串"
print(str1, type(str1)) # 字符串 <class 'str'>
# 1.字符串转义字符
# \n 换行
# \t 制表符(Tab
# \\ 标识反斜杠自身
# \' 单引号
# \" 双引
# uXXXX 标识Unicode字符
# 如果不需要将反斜杠作为转义符使用,可以在字符前面加r,表示原始字符串,反斜杠不会被转移
str2 = "\n"
print(str2)
str3 = "制表\t"
print(str3) # 制表 符
str4 = "反斜杠\\自身"
print(str4) # 反斜杠\自身
str5 = '单引"'
print(str5) # 双引号
str6 = r"原始字符串\n不会被转义"
print(str6) # 原始字符串\n不会被转义
# 2.字符串索引和切片
# 字符串中的每个字符都可以通过索引(下标)来访问。索引从0开始,也支持负数索引(-1表示最后一个字符,-2表示倒数第二个,以此类推)。
text = "Hello Python"
print("索引操作:")
print(f"字符串: '{text}'")
print(f"字符串长度{len(text)}") # 字符串长度12
print(f"正索引-text[0]:{text[0]}") # H
print(f"正索引-text[6]:{text[6]}") # P
print(f"负索引-text[-1]:{text[-1]}") # n
print(f"负索引-text[-6]:{text[-6]}") # P
# 切片(slice)可以用来获取字符串中的一部分,语法为 `str[start:end:step]`,其中:
# - `start`:起始索引(包含该位置,默认为0)
# - `end`:结束索引(不包含该位置,默认为字符串长度)
# - `step`:步长(默认为1,可以为负数实现反向切片)
text = "Hello Python Programming"
print(f"text[0:5]:{text[0:6]}") # Hello
print(f"text[6:12]: '{text[6:12]}'") # Python
print(f"text[:5]: '{text[:5]}'") # Hello (从开始到索引5)
print(f"text[13:]: '{text[13:]}'") # Programming (从索引13到结束)
print(f"text[-11:]: '{text[-11:]}'") # Programming (从倒数第11个到结束)
# 切片步长
print(f"text[::2]:{text[::2]}") # HloPto rgamn
print(f"text[1::2]: '{text[1::2]}'") # el yhnPormig (从索引1开始,步长为2)
print(f"text[::-1]: '{text[::-1]}'") # gnimmargorP nohtyP olleH (反转)
# 字符串操作方法
# 大小写转换
# upper()全部转大写
# lower() 全部转小写
# capitalize()首字母大写,其余小写
# title()每个单词首字母大写
# swapcase()大小写互换
text = "hello World of Python"
print(f"转大写{text.upper()}") # WORLD OF PYTHON
print(f"转小写{text.lower()}") # world of python
print(f"首字母大写{text.capitalize()}") # Hello world of python
print(f"每个单词首字母大写{text.title()}") # Hello World Of Python
print(f"大小写互换{text.swapcase()}") # HELLO wORLD OF pYTHON
# 查找和替换
# find(sub) 查找子串,返回索引,找不到返回-1
# rfind(sub) 从右侧查找
# index(sub) 找到子串,找不到抛出异常
# count(sub) 统计子串出现次数
# replace(old,new,count) 替换子串
text = "Hello World, Welcome to Python World"
print(f"查找Welcome出现的位置{text.find('Welcome')}") # 13
print(f"查找不存在的{text.find('java')}") # -1
print(f"从右侧查找{text.rfind('Python')}") # 24
print(f"从索引查找{text.index('Python')}") # 24
print(f"出现次数{text.count('Python')}") # 1
print(f"替换{text.replace('Python','Java')}") # Hello World, Welcome to Java World
# 字符串检查
# isalpha():是否全为字母
# isdigit():是否全为数字
# isalnum():是否全为字母或数字
# isspace():是否全为空白字符(如空格、制表符等)
# istitle():是否为标题格式(每个单词首字母大写)
# isupper():是否全为大写字母
# islower():是否全为小写字母
# startswith(): 是否以指定子串开头
# endswith(): 是否以指定子串结尾
def string_checks():
test_cases = [
"Hello123", # 字母数字
"12345", # 纯数字
"Hello", # 纯字母
" ", # 纯空格
"HELLO", # 全大写
"hello", # 全小写
"Hello World", # 包含空格
"", # 空字符串
]
print("字符串检查")
for s in test_cases:
print(
f"{s:12}: 字母={s.isalpha():5} 数字={s.isdigit():5} 数字字母={s.isalnum():5} 空格={s.isspace():5} 标题={s.istitle():5}"
)
# string_checks()
# 开头结尾检查
filename = "document.pdf"
url = "https://www.example.com"
print(f"\n文件{filename}是PDF嘛?{filename.endswith('pdf')}")
print(f"URL'{url}' 以https开头吗? {url.startswith('https')}")
# 去除空格和填充
# 去除空白字符和字符串填充方法用于格式化字符串内容。
# strip():去除字符串两端的空白字符(包括空格、制表符、换行等)
# lstrip():去除左侧空白
# rstrip():去除右侧空白-
# strip([chars]) 也可以去除指定字符(如'*'、'0'等)-
# center(width, fillchar):内容居中,两侧用fillchar填充
# ljust(width, fillchar):内容左对齐,右侧用fillchar填充
# rjust(width, fillchar):内容右对齐,左侧用fillchar填充
# zfill(width):左侧用0填充,常用于数字字符串
text = " Hello World "
print(f"原始: |{text}|")
# 去除字符串两边空格
print(f"去除字符串两边空格|{text.strip()}|")
# 去除左边空格
print(f"去除字符串左侧空格|{text.lstrip()}|")
# 去除右边有空格
print(f"去除字符串右侧空格|{text.rstrip()}|")
# 包含特定字符的字符串
text2 = "***Hello World***"
print(f"去除指定字符|{text2.strip("*")}|")
text3 = "Hello"
# 将字符串居中填充到20个字符宽度并输出
print(f"居中: |{text3.center(20)}|")
# 将字符串左对齐填充到20个字符宽度并输出
print(f"左对齐: |{text3.ljust(20)}|")
# 将字符串右对齐填充到20个字符宽度并输出
print(f"右对齐: |{text3.rjust(20)}|")
# 使用0在左侧填充字符串到10个字符宽度
print(f"右对齐: |{text3.zfill(10)}|") # 00000Hello
# 分割和连接
# split(sep=None, maxsplit=-1):将字符串按指定分隔符分割成列表,sep为分隔符,maxsplit为分割次数,默认全部分割。
# rsplit(sep=None, maxsplit=-1):从右侧开始分割,其他用法同split。
# splitlines(keepends=False):按行分割字符串,返回每一行组成的列表,keepends为True时保留换行符。
# join(iterable):用指定字符串连接可迭代对象中的元素,生成一个新的字符串。
csv_data = "apple,banana,orange,grape"
sentence = "Hello World of Python"
lines = "第一行\n第二行\n第三行"
print(f"csv分割{csv_data.split(',')}") # ['apple', 'banana', 'orange', 'grape']
print(f"句子分割{sentence.split()}") # ['Hello', 'World', 'of', 'Python']
print(f"限制分割{sentence.split(' ',2)}") # ['Hello', 'World', 'of Python']
print(f"按行分割{lines.splitlines()}") # ['第一行', '第二行', '第三行']
# 字符串连接
fruits = ["apple", "banana", "orange"]
print(f"字符串连接{','.join(fruits)}") # apple,banana,orange
print(f"字符串连接{'|'.join(fruits)}") # apple|banana|orange
# 字符串格式化
# f-string
# 语法:在字符串前加f,花括号{}中放变量或表达式。
# 例:f"姓名: {name}, 年龄: {age}"
# 优点:简洁、支持表达式、易读。
name = "Alice"
age = 25
salary = 5000.50
print("f-string格式化:")
print(f"姓名: {name}, 年龄: {age}")
print(f"薪资: ${salary:.2f}")
print(f"明年年龄: {age + 1}")
print(f"名字大写: {name.upper()}")
# 表达式和函数调用
items = ["apple", "banana", "orange"]
print(f"物品数量: {len(items)}")
print(f"第二个物品: {items[1]}")
# 格式化对齐
number = 42
print(f"右对齐: |{number:>10}|")
print(f"左对齐: |{number:<10}|")
print(f"居中对齐: |{number:^10}|")
print(f"零填充: |{number:010}|")
# format() 方法
# 语法:字符串中用{}占位,调用format()传入对应的值。
# 例:"{} is {} years old".format(name, age)
# 支持位置参数、关键字参数、格式控制。
# format() 方法
name = "Bob"
age = 30
print("format() 方法:")
print("{} is {} years old".format(name, age))
print("{0} is {1} years old. Hello {0}!".format(name, age))
print("{name} is {age} years old".format(name=name, age=age))
# 数字格式化
pi = 3.14159
print("PI = {:.2f}".format(pi))
print("二进制: {:b}".format(10))
print("十六进制: {:x}".format(255))
# % 操作符
# 语法:字符串中用%占位符,后面用%传入元组或字典。
# 例:"%s is %d years old" % (name, age)
# 占位符有%s(字符串)、%d(整数)、%f(浮点数)等。
# % 操作符 (传统方法)
name = "Charlie"
age = 35
print("% 格式化:")
print("%s is %d years old" % (name, age))
print("PI = %.3f" % 3.14159)
# 字符串不可变
# 字符串在Python中是不可变对象(immutable),这意味着一旦创建,字符串的内容就不能被直接修改。所有对字符串的操作(如拼接、替换、大小写转换等)都会返回一个新的字符串对象,原有字符串保持不变。
# 这种不可变性带来如下特点和好处:
# 安全性:字符串作为键(key)用于字典等哈希结构时,内容不会被意外更改,保证哈希值稳定。
# 多线程安全:多个线程可以安全地共享字符串对象,无需担心内容被修改。
# 高效缓存:Python可以对相同内容的字符串进行内部缓存和重用,提升性能。
# 注意:虽然不能直接修改字符串的某个字符,但可以通过切片、拼接等方式生成新的字符串。