Python字符串操作示例

本页面展示了Python中常见的字符串操作方法和实用示例,帮助你更好地理解和使用Python的字符串功能。

基本操作


# 字符串创建
text = "Hello, World!"
text2 = 'Python字符串'
text3 = """多行
字符串
示例"""

# 字符串拼接
result = "Hello" + " " + "World"  # 使用+号拼接
name = "Python"
greeting = f"Hello, {name}!"      # f-string格式化

# 字符串切片
text = "Python编程"
first_char = text[0]      # 获取第一个字符 'P'
sub_str = text[0:6]       # 切片获取子串 'Python'
reverse_str = text[::-1]  # 反转字符串 '程编nohtyP'
                

常用字符串方法


# 大小写转换
text = "Hello World"
print(text.upper())       # 'HELLO WORLD'
print(text.lower())       # 'hello world'
print(text.title())       # 'Hello World'

# 查找和替换
text = "Python编程学习"
print(text.find("编程"))   # 返回6
print(text.replace("Python", "Java"))  # 'Java编程学习'

# 分割和连接
text = "Python,Java,C++"
languages = text.split(",")  # ['Python', 'Java', 'C++']
joined = "-".join(languages) # 'Python-Java-C++'

# 去除空白
text = "  Python  "
print(text.strip())      # 'Python'
print(text.lstrip())     # 'Python  '
print(text.rstrip())     # '  Python'
                

字符串格式化


# f-string (推荐使用,Python 3.6+)
name = "Python"
age = 30
print(f"我正在学习{name},它已经{age}岁了")

# format()方法
print("我正在学习{},它已经{}岁了".format(name, age))
print("我正在学习{lang},它已经{years}岁了".format(
    lang=name, years=age))

# %操作符 (传统方式)
print("我正在学习%s,它已经%d岁了" % (name, age))

# 数字格式化
pi = 3.14159
print(f"π值保留两位小数:{pi:.2f}")  # 3.14
price = 1234.5678
print(f"价格:¥{price:,.2f}")       # ¥1,234.57
                

实用示例


# 密码强度检查
def check_password_strength(password):
    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    has_digit = any(c.isdigit() for c in password)
    is_long_enough = len(password) >= 8
    
    return all([has_upper, has_lower, has_digit, is_long_enough])

# 文本处理
def process_text(text):
    # 去除多余空白
    text = " ".join(text.split())
    # 转换为标题格式
    text = text.title()
    # 替换特殊字符
    text = text.replace("@", "at")
    return text

# URL解析
def parse_url(url):
    # 移除协议
    if "://" in url:
        url = url.split("://")[1]
    # 分离域名和路径
    parts = url.split("/", 1)
    domain = parts[0]
    path = parts[1] if len(parts) > 1 else ""
    return domain, path
                

注意事项

  • Python中的字符串是不可变对象,所有修改操作都会返回新的字符串
  • 使用f-string进行字符串格式化是Python 3.6+推荐的方式
  • 在处理大量字符串拼接时,推荐使用join()方法而不是+运算符
  • 处理Unicode字符串时要注意编码问题
  • 字符串切片操作可能会创建新的字符串对象,注意内存使用

相关链接