Python3 字符串详解

在 Python3 中,字符串(String)是最常用的数据类型之一,用于表示文本数据。Python 提供了丰富的字符串处理功能,使其成为文本处理和数据清洗的强大工具。以下是 Python3 字符串的详细介绍:

一、字符串基础

1. 定义字符串

使用单引号、双引号或三引号(用于多行字符串)定义:
 
s1 = 'Hello'          # 单引号
s2 = "World"          # 双引号
s3 = '''This is a 
multi-line string'''  # 三引号
s4 = """Triple double quotes"""  # 三引号(双引号)
 

2. 转义字符

使用反斜杠\转义特殊字符:
 
print('He said: "Hello!"')  # 输出: He said: "Hello!"
print('Line 1\nLine 2')     # 换行符
print('Tab\tSpacing')       # 制表符
print('Backslash: \\')      # 反斜杠本身
 

3. 原始字符串

使用r前缀忽略转义:
 
print(r'C:\Users\Admin')  # 输出: C:\Users\Admin
 

二、字符串操作

1. 拼接与重复

 
s1 = 'Hello'
s2 = 'World'
print(s1 + ' ' + s2)  # 拼接: Hello World
print(s1 * 3)        # 重复: HelloHelloHello
 

2. 索引与切片

s = 'Python'
print(s[0])         # 索引: P
print(s[-1])        # 负索引: n
print(s[2:5])       # 切片: tho
print(s[:3])        # 从头开始: Pyt
print(s[3:])        # 到末尾: hon
print(s[::-1])      # 反转: nohtyP
 

3. 字符串长度

s = 'Python'
print(len(s))  # 输出: 6
 

三、字符串格式化

1. 旧式格式化(%)

 
name = 'Alice'
age = 25
print('My name is %s and I am %d years old.' % (name, age))
# 输出: My name is Alice and I am 25 years old.
 

2. 新式格式化(format)

print('My name is {} and I am {} years old.'.format(name, age))
# 输出: My name is Alice and I am 25 years old.

# 带索引
print('{0} loves {1}'.format('Bob', 'Python'))  # Bob loves Python
 

3. f-strings(Python 3.6+)

print(f'My name is {name} and I am {age} years old.')
# 输出: My name is Alice and I am 25 years old.

# 表达式计算
x = 10
y = 20
print(f'The sum is {x + y}')  # 输出: The sum is 30
 

四、字符串方法

1. 大小写转换

s = 'Hello World'
print(s.upper())      # HELLO WORLD
print(s.lower())      # hello world
print(s.title())      # Hello World
print(s.capitalize()) # Hello world
 

2. 查找与替换

s = 'Hello World'
print(s.find('World'))    # 索引: 6
print(s.index('World'))   # 索引: 6
print(s.count('l'))       # 出现次数: 3
print(s.replace('World', 'Python'))  # Hello Python
 

3. 分割与连接

s = 'apple,banana,orange'
print(s.split(','))  # ['apple', 'banana', 'orange']

words = ['Hello', 'World']
print(' '.join(words))  # Hello World
 

4. 修剪与判断

s = '   Hello   '
print(s.strip())     # 去除两边空格: Hello
print(s.lstrip())    # 去除左边空格: Hello   
print(s.rstrip())    # 去除右边空格:    Hello

print('123'.isdigit())    # True
print('hello'.isalpha())  # True
print('Hello123'.isalnum()) # True
print('   '.isspace())    # True
 

五、字符串编码与解码

Python3 默认使用 Unicode 编码,支持多种编码转换:
 
 
s = '你好'
# 编码为bytes
b = s.encode('utf-8')  # b'\xe4\xbd\xa0\xe5\xa5\xbd'
b = s.encode('gbk')    # b'\xc4\xe3\xba\xc3'

# 解码为字符串
print(b.decode('utf-8'))  # 你好
print(b.decode('gbk'))    # 你好
 

六、字符串处理进阶

1. 正则表达式(re 模块)

import re

s = 'Hello 123 World 456'
# 查找所有数字
print(re.findall('\d+', s))  # ['123', '456']

# 替换
print(re.sub('\d+', 'NUM', s))  # Hello NUM World NUM
 

2. 字符串模板(string.Template)

from string import Template

t = Template('$name loves $language')
print(t.substitute(name='Alice', language='Python'))
# 输出: Alice loves Python
 

七、性能优化建议

  1. 避免循环拼接:使用join()方法代替+拼接,提高效率。
    # 低效
    s = ''
    for c in ['a', 'b', 'c']:
        s += c
    
    # 高效
    s = ''.join(['a', 'b', 'c'])
    
  2. 使用 f-strings:在 Python 3.6 + 中,f-strings 比format()更高效。

八、总结

  • 定义方式:单引号、双引号、三引号,支持转义和原始字符串。
  • 操作:拼接、索引、切片、格式化等。
  • 方法:大小写转换、查找替换、分割连接、修剪判断等。
  • 编码:Unicode 编码,支持多种编码格式转换。
  • 进阶工具:正则表达式、字符串模板。

Python 字符串的丰富功能使其成为文本处理的首选语言,掌握这些技巧能显著提升数据处理和文本分析的效率。

posted on 2025-11-13 09:17  小陶coding  阅读(80)  评论(0)    收藏  举报