字符串的定义与创建

字符串是Python中用于表示文本数据的基本数据类型,由单引号(')、双引号(")或三引号('''""")包裹的内容构成。

str1 = 'Hello'
str2 = "World"
str3 = '''Multi-line
string'''

字符串的索引与切片

字符串支持通过索引访问单个字符(从0开始)或通过切片获取子串(左闭右开区间)。

s = "Python"
print(s[0])    # 输出 'P'(正向索引)
print(s[-1])   # 输出 'n'(反向索引)
print(s[1:4])  # 输出 'yth'(切片)

字符串的常用方法

  • 大小写转换

    s = "hello"
    print(s.upper())      # 'HELLO'
    print(s.capitalize()) # 'Hello'
    

  • 查找与替换

    s = "apple,banana"
    print(s.find('banana'))  # 返回索引6
    print(s.replace('apple', 'orange')) # 'orange,banana'
    

  • 分割与连接

    s = "a,b,c"
    print(s.split(','))    # ['a', 'b', 'c']
    print('-'.join(['x', 'y', 'z'])) # 'x-y-z'
    

字符串格式化

Python支持多种字符串格式化方式,包括%操作符、str.format()和f-string(推荐)。

name = "Alice"
age = 25
print(f"{name} is {age} years old.") # f-string(Python 3.6+)
print("{} is {} years old.".format(name, age)) # str.format

字符串的不可变性

字符串是不可变对象,修改字符串会生成新对象而非直接修改原字符串。

s = "abc"
s[0] = 'x'  # 报错!不可直接修改
new_s = 'x' + s[1:]  # 正确:生成新字符串

转义字符与原始字符串

  • 转义字符(如\n\t)用于表示特殊符号。
  • 原始字符串(前缀r)会忽略转义字符。
print("Line1\nLine2")  # 换行输出
print(r"C:\path\to\file")  # 输出原始路径

字符串编码与解码

Python 3中字符串默认使用Unicode编码(str类型),可通过encode()decode()与字节串(bytes)转换。

s = "中文"
b = s.encode('utf-8')  # 转为字节串
print(b.decode('utf-8')) # 解码回字符串

字符串操作符与函数

  • 操作符+(拼接)、*(重复)、in(包含检查)。
  • 内置函数len()ord()(字符转Unicode码)、chr()(Unicode码转字符)。
print("Py" + "thon")   # 'Python'
print("ha" * 3)        # 'hahaha'
print('ell' in 'hello') # True

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐