1. 字符串的基本概念 #

s1 = "双引号"
s2 = '单引号'
s3 = """多行
文本"""

print(len(s3))           # 字符个数
print(type(s1))          # <class 'str'>
path = r"C:\Users\data\new.txt"

2. 索引与切片 #

text = "Hello Python"

print(text[0])       # H
print(text[-1])      # n(最后一个)
print(text[0:5])     # Hello
print(text[6:])      # Python

3. 常用方法 #

方法 用途
strip() 去掉首尾空白(表单、CSV 很常见)
lower() / upper() 大小写转换(比较、规范化)
split(sep) 按分隔符拆成列表
join(iterable) 用分隔符连接列表为字符串
replace(old, new) 替换子串
startswith() / endswith() 判断前缀/后缀(URL、文件名)
in 判断是否包含子串
email = "  User@Example.COM  "
print(email.strip().lower())              # user@example.com

csv = "apple,banana,orange"
fruits = csv.split(",")                   # ['apple', 'banana', 'orange']
print(", ".join(fruits))                  # apple, banana, orange

url = "https://api.example.com/users"
print(url.startswith("https"))            # True

filename = "report.pdf"
print(filename.endswith(".pdf"))          # True

msg = "操作成功"
print("成功" in msg)                      # True
text = "Hello World"
print(text.find("World"))                 # 6,找不到返回 -1
print(text.replace("World", "Python"))    # Hello Python

4. 字符串格式化 #

name = "Alice"
age = 25
print(f"用户: {name}, 年龄: {age}")
print(f"明年: {age + 1}")

5. 编码 #

b = "你好".encode("utf-8")
print(b.decode("utf-8"))   # 你好

6. 项目开发要点 #