Skip to content

字符串与Unicode:码点、编码与文本处理 ​

字符串基础 ​

Python 3字符串是Unicode文本。

python
s = "Hello, 世界"
print(len(s))  # 9(字符数,不是字节数)
print(s[7])    # '世'

# 字符串方法
print(s.upper())     # "HELLO, 世界"
print(s.startswith("Hello"))  # True
print(s.split(", "))  # ['Hello', '世界']

Unicode与编码 ​

python
text = "Python编程"

# 编码为字节
utf8_bytes = text.encode('utf-8')
print(utf8_bytes)  # b'Python\xe7\xbc\x96\xe7\xa8\x8b'

# 解码回字符串
decoded = utf8_bytes.decode('utf-8')
print(decoded)  # 'Python编程'

字符串格式化 ​

python
name = "Alice"
age = 30

# f-string(推荐)
print(f"{name} is {age} years old")

# format方法
print("{} is {} years old".format(name, age))

# 格式化选项
pi = 3.14159
print(f"Pi: {pi:.2f}")  # "Pi: 3.14"

练习 ​

  1. 字符串反转:反转字符串(包括Unicode字符)。
  2. 单词统计:统计文本中单词数量。
  3. 编码转换:UTF-8字节转UTF-16。
  4. 格式化表格:用f-string格式化数据表格。
  5. 回文判断:判断字符串是否为回文。

答案:第三章答案

下一节:字节与二进制

用心记录每一步成长