返回专栏
· 20 分钟阅读

Python 字符串 str 的定义与操作


一、字符串的基本概念

1.1 什么是字符串

字符串(String)是由一系列字符组成的文本数据,用于表示文字、符号、数字文本以及其他 Unicode 字符。

Python 使用内置类型 str 表示字符串。

name = "Python"
message = "Hello, World!"
number_text = "12345"

print(type(name))  # <class 'str'>
print(type(message))  # <class 'str'>

字符串属于序列类型,具有以下特征:

  • 有序:字符按照一定顺序排列。
  • 可索引:可以通过索引访问指定位置的元素。
  • 可切片:可以提取指定范围的子字符串。
  • 可迭代:可以使用 for 遍历字符串。
  • 不可变:创建后不能直接修改其中的字符。
  • 支持序列操作:支持长度计算、成员判断、拼接和重复等操作。
text = "Python"

print(len(text))       # 6
print(text[0])         # P
print(text[-1])        # n
print("Py" in text)    # True
print(list(text))      # ['P', 'y', 't', 'h', 'o', 'n']

1.2 字符串是 Unicode 文本序列

Python 3 的 str 用于表示 Unicode 文本。

Unicode 为世界上绝大多数书写系统中的字符分配码点,例如:

字符 Unicode 码点
A U+0041
中 U+4E2D
€ U+20AC