On this page

Python 字符串

Python 字符串详解

字符串是 Python 中最常用的数据类型之一,用于表示文本信息。以下是 Python 字符串的全面介绍:

1. 字符串创建

Python 中的字符串可以使用单引号、双引号或三引号创建:

# 单引号
str1 = 'Hello World'

# 双引号
str2 = "Python Programming"

# 三引号(多行字符串)
str3 = """这是一个
多行
字符串"""

2. 字符串基本操作

字符串连接

s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)  # "Hello World"

字符串重复

print("Hi" * 3)  # "HiHiHi"

字符串索引

s = "Python"
print(s[0])  # 'P' (第一个字符)
print(s[-1]) # 'n' (最后一个字符)

字符串切片

s = "Python Programming"
print(s[0:6])   # "Python" (索引0到5)
print(s[7:])    # "Programming" (从索引7到末尾)
print(s[:6])    # "Python" (从开始到索引5)
print(s[::2])   # "Pto rgamn" (步长为2)

3. 字符串常用方法

大小写转换

s = "Python Programming"
print(s.lower())      # "python programming"
print(s.upper())      # "PYTHON PROGRAMMING"
print(s.title())      # "Python Programming"
print(s.capitalize()) # "Python programming"

查找和替换

s = "Python Programming"
print(s.find("Pro"))     # 7 (返回索引位置)
print(s.replace("P", "J")) # "Jython Jrogramming"

拆分和连接

s = "Python,Java,C++"
print(s.split(","))      # ['Python', 'Java', 'C++']

words = ["Python", "is", "great"]
print(" ".join(words))   # "Python is great"

去除空白字符

s = "   Python   "
print(s.strip())     # "Python" (去除两端空格)
print(s.lstrip())    # "Python   " (去除左端空格)
print(s.rstrip())    # "   Python" (去除右端空格)

字符串判断

s = "Python123"
print(s.isalpha())   # False (是否全是字母)
print(s.isdigit())   # False (是否全是数字)
print(s.isalnum())   # True (是否字母或数字)
print(s.startswith("Py"))  # True
print(s.endswith("23"))    # True

4. 字符串格式化

f-string (Python 3.6+ 推荐)

name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")

format() 方法

print("My name is {} and I'm {} years old.".format(name, age))
print("My name is {1} and I'm {0} years old.".format(age, name))

% 格式化 (旧式)

print("My name is %s and I'm %d years old." % (name, age))

5. 字符串编码

Python 3 默认使用 Unicode 编码(UTF-8):

s = "你好世界"
print(len(s))        # 4 (字符数)
print(s.encode())    # b'\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c'

6. 转义字符

转义字符描述
\n换行
\t制表符
\\反斜杠
\'单引号
\"双引号
\r回车
print("Line1\nLine2")  # 两行文本
print("C:\\path\\to\\file")  # 显示路径

7. 字符串不可变性

Python 字符串是不可变对象:

s = "Python"
# s[0] = "J"  # 会报错,字符串不可变

# 正确做法是创建新字符串
s = "J" + s[1:]
print(s)  # "Jython"

8. 字符串高级操作

字符串反转

s = "Python"
print(s[::-1])  # "nohtyP"

字符串对齐

s = "Python"
print(s.ljust(10, "-"))  # "Python----"
print(s.rjust(10, "-"))  # "----Python"
print(s.center(10, "-")) # "--Python--"

字符串翻译

trans = str.maketrans("aeiou", "12345")
s = "This is an example"
print(s.translate(trans))  # "Th3s 3s 1n 2x1mpl2"

9. 字符串与字节串转换

# 字符串转字节串
s = "Python"
b = s.encode('utf-8')  # b'Python'

# 字节串转字符串
s2 = b.decode('utf-8')  # "Python"

10. 实际应用示例

统计字符出现次数

text = "hello world"
count = text.count('l')
print(f"'l' appears {count} times")  # 'l' appears 3 times

检查回文字符串

def is_palindrome(s):
    return s == s[::-1]

print(is_palindrome("madam"))  # True

密码强度检查

def check_password(password):
    if len(password) < 8:
        return "密码太短"
    if not any(c.isupper() for c in password):
        return "需要包含大写字母"
    if not any(c.isdigit() for c in password):
        return "需要包含数字"
    return "密码强度足够"

print(check_password("Python123"))  # "密码强度足够"

总结

Python 字符串功能强大且灵活,提供了丰富的内置方法用于文本处理。掌握字符串操作是 Python 编程的基础,对于数据处理、Web 开发和日常脚本编写都至关重要。