查看: 154|回复: 0

Python字符串常用操作技巧:定义切片格式化与内置方法详解

[复制链接]
发表于 半小时前 | 显示全部楼层 |阅读模式
字符串是Python开发中接触最频繁的数据类型之一,无论是清洗用户输入、解析日志文件,还是拼接SQL条件,都离不开对字符串的灵活操作。本文按照实际使用频率,系统梳理字符串的定义、转义、格式化、索引切片、遍历以及常用内置方法,并给出可直接运行的代码示例。

一、字符串的几种定义方式

字符串本质上是字符的有序序列,使用引号包裹即可创建。单引号和双引号在功能上完全等价,选择依据主要是字符串内容是否包含引号;三引号则用于多行文本。
  1. # 单引号
  2. name = '张三'
  3. # 双引号
  4. city = "北京"
  5. # 三引号支持换行
  6. desc = """这是一个
  7. 多行字符串"""
  8. content = '''同样支持
  9. 多行文本'''
  10. # 空字符串的三种写法
  11. empty1 = ""
  12. empty2 = ''
  13. empty3 = str()
复制代码

如果字符串内部包含单引号,外层就用双引号;反之同理。也可以统一用反斜杠转义,但可读性稍差。
  1. msg1 = "I'm a student"
  2. msg2 = '他说:"你好"'
  3. msg3 = 'I\'m a student'
复制代码

二、转义字符与原始字符串

反斜杠在字符串中承担转义职责,常见的转义符包括:\' 表示单引号,\" 表示双引号,\\ 表示反斜杠本身,\n 换行,\t 制表符,\r 回车,\b 退格。
  1. print("第一行\n第二行")
  2. print("姓名\t年龄\t城市")
  3. print("张三\t25\t北京")
复制代码

写Windows路径时,反斜杠容易和转义符冲突。比如 "C:\new\test" 里的 \n 会被当成换行。解决办法是使用原始字符串,在引号前加 r:
  1. path = r"C:\new\test"
复制代码

原始字符串在正则表达式和文件路径场景中非常实用,能省去大量双反斜杠的书写。

三、字符串格式化的三种方式

1. % 格式化(旧式)
  1. name = "张三"
  2. age = 25
  3. print("我叫%s,今年%d岁" % (name, age))
复制代码

%s 对应字符串,%d 对应整数,%f 对应浮点数。

2. format() 方法

支持位置参数、索引参数和变量名参数:
  1. print("我叫{},今年{}岁".format(name, age))
  2. print("我叫{1},今年{0}岁".format(age, name))
  3. print("我叫{name},今年{age}岁".format(name=name, age=age))
复制代码

3. f-string(Python 3.6+)

f-string 是当前最推荐的方式,可读性最好、性能也最高。花括号内可以直接写变量名或表达式:
  1. x, y = 3, 5
  2. print(f"{x} + {y} = {x + y}")
  3. price = 12.345
  4. print(f"价格:{price:.2f}元")
复制代码

四、索引规则与常见陷阱

字符串中的每个字符都有位置编号,正向索引从0开始,负向索引从 -1 开始。以 "Python" 为例:
  1. s = "Python"
  2. print(s[0])  # P
  3. print(s[3])  # h
  4. print(s[-1]) # n
  5. print(s[-3]) # h
复制代码

索引对应关系:
字符 P y t h o n
正向 0 1 2 3 4 5
负向 -6 -5 -4 -3 -2 -1

两个需要特别注意的点:

1. 索引越界会抛出 IndexError,所以在动态取字符时要注意长度判断。
2. 字符串是不可变对象,不能通过索引直接修改字符:s[0] = "J" 会报 TypeError。

五、切片操作语法与步长

切片是从字符串中截取子串的最直接方式,语法为 [start:end:step],遵循左闭右开规则,即包含 start 位置,不包含 end 位置。
  1. s = "Hello, World!"
  2. print(s[0:5])   # Hello
  3. print(s[7:12])  # World
  4. print(s[:5])    # Hello
  5. print(s[7:])    # World!
  6. print(s[:])     # 整个字符串
  7. print(s[-6:-1]) # World
复制代码

步长的典型用法包括间隔取值和反转字符串:
  1. s = "abcdefghij"
  2. print(s[::2])  # acegi
  3. print(s[1::2]) # bdfhj
  4. print(s[::-1]) # jihgfedcba
复制代码

切片比索引容错性强得多:即使 end 超过字符串长度也不会报错,最多返回空字符串。例如 s = "abc",s[0:10] 返回 "abc",s[10:20] 返回 ""。

六、遍历字符串的四种姿势

1. 直接遍历字符:
  1. for char in "Python":
  2.     print(char)
复制代码

2. 通过索引遍历:
  1. s = "Python"
  2. for i in range(len(s)):
  3.     print(s[i])
复制代码

3. 使用 enumerate 同时拿到索引和值:
  1. for index, char in enumerate("Python"):
  2.     print(f"索引{index}:{char}")
复制代码

4. 遍历时判断字符类型,可结合 isdigit 和 isalpha 等判断方法:
  1. s = "Hello123"
  2. for char in s:
  3.     if char.isdigit():
  4.         print(f"{char} 是数字")
  5.     elif char.isalpha():
  6.         print(f"{char} 是字母")
复制代码

七、高频内置方法分类整理

1. 大小写转换
  1. text = "python is FUN"
  2. print(text.upper())      # PYTHON IS FUN
  3. print(text.lower())      # python is fun
  4. print(text.capitalize()) # Python is fun
  5. print(text.title())      # Python Is Fun
  6. print(text.swapcase())   # PYTHON IS fun
复制代码

2. 去除空白字符

strip() 去除两端空白,lstrip() 只去左侧,rstrip() 只去右侧。空白包括空格、换行、制表符。
  1. text = " hello \n"
  2. print(text.strip())   # hello
  3. print(text.lstrip())  # hello \n
  4. print(text.rstrip())  #  hello
复制代码

strip 也能指定要去除的字符:
  1. text = "!!!hello!!!"
  2. print(text.strip("!")) # hello
复制代码

3. 查找与判断

find 找不到时返回 -1,index 找不到会抛 ValueError;rfind 从右向左查找;startswith/endswith 判断前后缀;count 统计出现次数。
  1. s = "hello world hello"
  2. print(s.find("world"))       # 6
  3. print(s.find("python"))      # -1
  4. print(s.index("world"))      # 6
  5. print(s.startswith("hello")) # True
  6. print(s.endswith("hello"))   # True
  7. print(s.count("hello"))      # 2
复制代码

4. 拆分与拼接

split 按指定分隔符拆成列表,可以加第二个参数限制最大拆分次数;splitlines 按换行符拆分;join 则用于将可迭代对象拼接成字符串。
  1. data = "apple,banana,orange"
  2. print(data.split(","))  # ['apple', 'banana', 'orange']
  3. data = "a,b,c,d"
  4. print(data.split(",", 2))  # ['a', 'b', 'c,d']
  5. text = "第一行\n第二行\n第三行"
  6. print(text.splitlines())  # ['第一行', '第二行', '第三行']
  7. items = ['a', 'b', 'c']
  8. print("-".join(items))  # a-b-c
复制代码

5. 替换

replace 支持指定替换次数,默认替换全部。
  1. s = "hello world hello"
  2. print(s.replace("hello", "hi"))       # hi world hi
  3. print(s.replace("hello", "hi", 1))    # hi world hello
复制代码

6. 对齐与填充

center、ljust、rjust 分别实现居中、左对齐、右对齐,可以指定填充字符;zfill 是右对齐并用 0 填充,常用于数字补零。
  1. s = "hello"
  2. print(s.center(11, "*"))  # ***hello***
  3. print(s.ljust(10, "-"))  # hello-----
  4. print(s.rjust(10, "-"))  # -----hello
  5. print(s.zfill(10))        # 00000hello
复制代码

7. 判断类型

isalpha 判断是否全为字母,isdigit 判断是否全为数字,isalnum 判断是否字母或数字组合,isspace 判断是否空白,islower/isupper 判断大小写,istitle 判断是否符合标题格式。
  1. print("hello".isalpha())  # True
  2. print("123".isdigit())    # True
  3. print("hello123".isalnum()) # True
  4. print(" ".isspace())     # True
  5. print("Hello".istitle())  # True
复制代码

八、记忆要点

字符串相关知识可以按定义、转义、格式化、索引、切片、遍历、常用方法这七个维度去掌握。日常开发中,格式化优先使用 f-string,路径和正则用原始字符串 r"",切片注意左闭右开,查找时如果不需要异常就用 find 而不是 index。

方法记不住也没关系,Python 提供了内置帮助接口:
  1. dir(str)
  2. help(str.replace)
复制代码

多写几遍代码,这些操作自然会形成肌肉记忆。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-8-26 10:51 , Processed in 0.020273 second(s), 18 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部