Featured image of post Python Basic 05 字符串处理

Python Basic 05 字符串处理

本篇文章主要介绍Python的字符串处理

创建字符串 (★ω★)

1
2
3
4
5
6
# 三种引号创建字符串
str1 = '单引号字符串'
str2 = "双引号字符串"
str3 = '''三引号可以
跨行
的字符串'''

基础操作 (* ̄▽ ̄)b

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
s = "Hello Python"

# 字符串长度
len(s)  # 12

# 索引访问
s[0]    # 'H' (第一个字符)
s[-1]   # 'n' (最后一个字符)s

# 切片操作
s[0:5]  # 'Hello' (第0到4个字符)
s[6:]   # 'Python' (第6个到末尾)
s[::2]  # 'HloPto' (每隔一个字符)

字符串常用方法 ヾ(^▽^*)))

修改字符串

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 转换大小写
"hello".upper()       # 'HELLO'
"HELLO".lower()       # 'hello'
"hello world".title() # 'Hello World'
"hello world".capitalize() # 'Hello world'

# 替换
"hello".replace('l', 'L')  # 'heLLo'

# 去除空白
"  hello  ".strip()   # 'hello'
"  hello  ".lstrip()  # 'hello  '
"  hello  ".rstrip()  # '  hello'

拼接与分割 (ノ◕ヮ◕)ノ*:・゚✧

1
2
3
4
5
6
7
8
# 拼接
", ".join(["apple", "banana", "orange"])  # 'apple, banana, orange'

# 分割
"apple,banana,orange".split(",")  # ['apple', 'banana', 'orange']

# 按行分割
"line1\nline2\nline3".splitlines()  # ['line1', 'line2', 'line3']

查找与判断 (= ̄ω ̄=)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 查找位置
"hello".find('l')     # 2 (第一个'l'的位置)
"hello".rfind('l')    # 3 (最后一个'l'的位置)
"hello".index('e')    # 1 (类似于find但如果找不到会报错)

# 判断内容
"123".isdigit()      # True (全是数字)
"abc".isalpha()      # True (全是字母)
"abc123".isalnum()   # True (字母或数字)
"hello".startswith('he')  # True
"hello".endswith('lo')    # True

格式化字符串 (`・ω・´)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 1. % 格式化 (老方法)
"Hello, %s!" % "World"  # 'Hello, World!'
"%d + %d = %d" % (1, 2, 1+2)  # '1 + 2 = 3'

# 2. format方法
"Hello, {}!".format("World")  # 'Hello, World!'
"{1} {0} {1}".format("world", "hello")  # 'hello world hello'

# 3. f-string (Python 3.6+)
name = "Alice"
age = 25
f"My name is {name} and I'm {age} years old."

转义字符 (⊙ˍ⊙)

1
2
3
4
print("换行\n制表符\t双引号\"单引号\'反斜杠\\")
# 输出:
# 换行
# 制表符    双引号"单引号'反斜杠\

其他有用操作 ٩(◕‿◕。)۶

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 字符串重复
"Hi" * 3  # 'HiHiHi'

# 对齐
"hello".ljust(10)   # 'hello     '
"hello".rjust(10)   # '     hello'
"hello".center(10)  # '  hello   '

# 计数
"hello hello".count('l')  # 4 (统计'l'出现的次数)

# 判断空白字符
"   ".isspace()  # True

# 反转字符串
s = "Python"
s[::-1]  # 'nohtyP'

# 多条件分割
import re
re.split(r'[,;|\s]\s*', "one,two;three|four five")
# ['one', 'two', 'three', 'four', 'five']

总结

字符串操作真的是Python编程中最常用的技能之一呢!(ノ≧∀≦)ノ 多加练习才能熟练掌握哦!(•̀ᴗ•́)و ̑̑

Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计