Python 字符串操作 | 豆包MarsCode AI刷题

92 阅读5分钟

Python 字符串操作总结

Python 中的字符串是不可变序列类型,意味着一旦创建就不能修改。然而,Python 提供了丰富的内置方法和功能来处理字符串,使得字符串操作既简单又强大。以下是关于 Python 字符串操作的详细总结。

1. 创建字符串

  • 使用单引号 '、双引号 " 或三引号 '''/""" 创建字符串。
    s1 = 'Hello'
    s2 = "World"
    s3 = '''This is a multi-line string.'''
    

2. 字符串拼接与重复

  • 使用 + 进行字符串拼接。
    greeting = "Hello" + " " + "World"
    print(greeting)  # 输出: Hello World
    
  • 使用 * 进行字符串重复。
    repeated = "Hi" * 3
    print(repeated)  # 输出: HiHiHi
    

3. 访问字符

  • 使用索引访问字符串中的单个字符,索引从0开始。
    s = "Python"
    print(s[0])  # 输出: P
    print(s[-1]) # 输出: n
    

4. 切片操作

  • 使用切片 [start:end:step] 获取子字符串。
    s = "Python"
    print(s[0:3])   # 输出: Pyt
    print(s[:3])    # 输出: Pyt
    print(s[3:])    # 输出: hon
    print(s[::-1])  # 输出: nohtyP (反转字符串)
    

5. 字符串方法

Python 提供了大量的内置方法来处理字符串:

  • 查找和替换

    • find(sub)index(sub):查找子字符串的位置(find 返回 -1 如果未找到,index 抛出异常)。
    • replace(old, new):替换所有出现的子字符串。
      s = "hello world"
      print(s.find("world"))  # 输出: 6
      print(s.replace("world", "universe"))  # 输出: hello universe
      
  • 大小写转换

    • upper():将字符串转换为大写。
    • lower():将字符串转换为小写。
    • capitalize():将字符串的第一个字母大写,其余小写。
    • title():将每个单词的首字母大写。
      s = "hello world"
      print(s.upper())       # 输出: HELLO WORLD
      print(s.lower())       # 输出: hello world
      print(s.capitalize())  # 输出: Hello world
      print(s.title())       # 输出: Hello World
      
  • 去除空白字符

    • strip():去除字符串两端的空白字符。
    • lstrip():去除字符串左边的空白字符。
    • rstrip():去除字符串右边的空白字符。
      s = "   hello world   "
      print(s.strip())  # 输出: hello world
      
  • 分割和连接

    • split(sep):根据分隔符 sep 分割字符串为列表。
    • join(iterable):将可迭代对象中的元素用指定字符串连接。
      s = "apple,banana,orange"
      fruits = s.split(',')
      print(fruits)  # 输出: ['apple', 'banana', 'orange']
      
      joined = '-'.join(fruits)
      print(joined)  # 输出: apple-banana-orange
      
  • 检查字符串内容

    • startswith(prefix)endswith(suffix):检查字符串是否以特定前缀或后缀开头/结尾。
    • isalpha()isdigit()isalnum()isspace() 等:检查字符串的内容类型。
      s = "hello"
      print(s.startswith("he"))  # 输出: True
      print(s.isalpha())         # 输出: True
      

6. 格式化字符串

  • 使用 % 操作符

    name = "Alice"
    age = 30
    print("My name is %s and I am %d years old." % (name, age))
    
  • 使用 .format() 方法

    print("My name is {} and I am {} years old.".format(name, age))
    
  • 使用 f-string(f"...")

    print(f"My name is {name} and I am {age} years old.")
    

7. 编码与解码

  • 编码:将字符串转换为字节序列。
  • 解码:将字节序列转换回字符串。
    original = "你好,世界"
    encoded = original.encode('utf-8')
    decoded = encoded.decode('utf-8')
    print(decoded)  # 输出: 你好,世界
    

8. 正则表达式

Python 的 re 模块提供了强大的正则表达式支持,用于复杂的字符串匹配和处理。

import re

pattern = r'\b[A-Za-z]+\b'  # 匹配单词
text = "The quick brown fox jumps over the lazy dog."
matches = re.findall(pattern, text)
print(matches)  # 输出: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

结论

Python 的字符串操作功能丰富且易于使用,涵盖了从基本的字符串创建和拼接到高级的正则表达式处理。掌握这些操作不仅能提升编程效率,还能帮助解决各种实际问题。对于初学者来说,建议多加练习,结合实际项目进行应用,逐步积累经验。

题目解析

题目描述: 编写一个函数 reverseWords,接收一个字符串作为参数,返回一个新的字符串,其中每个单词的字符顺序被反转,但单词之间的顺序保持不变。

思路

  1. 分割字符串:首先使用空格将输入字符串分割成单词列表。
  2. 反转单词:对每个单词进行反转操作。
  3. 重新组合:将反转后的单词重新用空格连接成新的字符串。

图解: 假设输入字符串为 "hello world"

  • 分割后得到列表 ["hello", "world"]
  • 反转每个单词得到 ["olleh", "dlrow"]
  • 最终组合成新字符串 "olleh dlrow"

代码详解

python
深色版本
def reverseWords(s: str) -> str:
    # Step 1: Split the string into words using space as delimiter
    words = s.split()
    
    # Step 2: Reverse each word in the list
    reversed_words = [word[::-1] for word in words]
    
    # Step 3: Join the reversed words with spaces to form the final string
    return ' '.join(reversed_words)

# 测试代码
if __name__ == "__main__":
    test_string = "hello world"
    print(f"Original String: {test_string}")
    print(f"Reversed Words: {reverseWords(test_string)}")

知识总结

在使用豆包MarsCode AI刷题的过程中,总结了以下几个关于 Python 字符串处理的新知识点:

  1. 字符串切片:Python 的切片功能非常强大,例如 s[::-1] 可以轻松实现字符串反转。这不仅适用于整个字符串,也适用于子字符串。
  2. 字符串方法:Python 提供了许多内置字符串方法,如 split()join()replace() 等,这些方法可以大大简化字符串操作。
  3. 列表推导式:通过列表推导式 [expression for item in iterable] 可以简洁地生成新的列表,尤其适合批量处理字符串或数字序列。
  4. 格式化字符串:使用 f-string(f"...")或 .format() 方法可以方便地插入变量值,提高代码可读性和灵活性。