Python基础之字符串常见操作经典实例详解

Python基础之字符串常见操作经典实例详解
最新回答
听闻国民小仙女

2026-02-05 21:12:32

Python字符串常见操作经典实例详解如下:

1. 字符串切片
  • 基础切片:str[beg:end]从下标beg开始切取到end-1,区间为左闭右开[beg, end)。str = 'python str'print(str[3:6]) # 输出: tho
  • 带步长的切片:str[beg:end:step]每隔step个字符取一个,区间仍为[beg, end)。print(str[2:7:2]) # 输出: yhn
2. 原始字符串
  • 在字符串前加r或R,取消转义字符的特殊含义。print(r'n') # 输出: n(而非换行)
3. 字符串重复
  • str * n或n * str:将字符串重复n次。str = "hi"print(str * 2) # 输出: hihi
4. 成员检测
  • in/not in:检测子字符串是否存在。str = 'python'print('py' in str) # 输出: True
5. 常用函数
  • 去空格:

    strip():去除首尾空格。

    lstrip():去除左侧空格。

    rstrip():去除右侧空格。

    str = ' python str 'print(str.strip()) # 输出: python str
  • 分隔字符串:

    split():默认按空格分隔,返回列表。

    split(sep):按指定分隔符sep分割。

    splitlines():按行分隔(支持n、r等)。

    str = '1,2,3'print(str.split(',')) # 输出: ['1', '2', '3']
  • 拼接字符串:

    join(seq):用指定字符连接序列元素。

    str = '-'seq = ('a', 'b', 'c')print(str.join(seq)) # 输出: a-b-c
  • 统计字符次数:

    count(sub[, beg, end]):统计子字符串出现次数。

    str = "thing example....wow!!!"print(str.count('i', 0, 5)) # 输出: 1
6. 子字符串检测
  • 查找索引:

    find(sub):返回子字符串首次出现的索引,未找到返回-1。

    index(sub):同find,但未找到时抛出ValueError。

    rfind()/rindex():从右侧开始查找。

    str1 = "this is string example....wow!!!"print(str1.find("exam")) # 输出: 15
7. 前缀与后缀检测
  • startswith(prefix[, beg, end]):检查是否以指定前缀开头。
  • endswith(suffix[, beg, end]):检查是否以指定后缀结尾。str = "this is string example....wow!!!"print(str.startswith('this')) # 输出: True
8. 分割与替换
  • 分割:

    partition(sep):返回三元组(左, sep, 右)。

    rpartition(sep):从右侧分割。

    str = "
    http://www.baidu.com/"print
    (str.partition("://")) # 输出: ('http', '://', 'www.baidu.com/')
  • 替换:

    replace(old, new[, max]):替换字符串,max限制替换次数。

    str = "thing example....wow!!!"print(str.replace("is", "was", 2)) # 输出: thwas was example....wow!!!
9. 字符串组成检测
  • 数字检测:

    isdigit():是否全为数字(如"123")。

    isnumeric()/isdecimal():针对Unicode数字。

  • 字母检测:

    isalpha():是否全为字母。

    isalnum():是否为字母或数字。

  • 其他检测:

    isspace():是否全为空格。

    islower()/isupper():大小写检测。

    str = "123"print(str.isdigit()) # 输出: True
10. 字符串处理
  • 大小写转换:

    capitalize():首字母大写,其余小写。

    lower()/upper():全小写/大写。

    swapcase():大小写互换。

  • 极值与长度:

    max(str)/min(str):返回ASCII值最大/最小的字符。

    len(str):字符串长度。

    str = "Python"print(str.lower()) # 输出: python
11. 格式化输出
  • 居中填充:

    center(width[, fillchar]):居中并填充字符至指定宽度。

    str = "wow"print(str.center(10, '*')) # 输出: *wow
  • 靠右填充:

    zfill(width):右对齐,左侧填充0。

    str = "42"print(str.zfill(5)) # 输出: 00042
  • 传统格式化:

    %格式化:%s(字符串)、%d(整数)等。

    print("Name: %s, Age: %d" % ("Alice", 25)) # 输出: Name: Alice, Age: 25
  • format方法:

    按位置或关键字参数格式化。

    print("{1}, {0}".format("b", "a")) # 输出: a, b

总结:Python字符串操作涵盖切片、查找、替换、格式化等,灵活运用这些方法可高效处理文本数据。