Python 字符串基本操作 | AI生成和翻译

Home 2025.12

问题:Python 中字符串的基本操作有哪些?

答案:

Python 中的字符串是不可变的字符序列。它们支持各种内置操作和方法进行操作。

常见的字符串基本操作

常用字符串方法

示例

s = "Hello, World!"

# 长度
len(s)                    # 13

# 索引和切片
s[0]                      # 'H'
s[-1]                     # '!'
s[0:5]                    # 'Hello'
s[7:]                     # 'World!'
s[:-7]                    # 'Hello,'

# 大小写转换
s.upper()                 # 'HELLO, WORLD!'
s.lower()                 # 'hello, world!'

# 替换
s.replace("World", "Python")  # 'Hello, Python!'

# 分割和连接
s.split(",")              # ['Hello', ' World!']
" ".join(["Hello", "Grok"])  # 'Hello Grok'

# 移除空白字符
"  spaced  ".strip()      # 'spaced'

# 查找
s.find("World")           # 7
s.find("xyz")             # -1

# 以...开头/结尾
s.startswith("Hello")     # True
s.endswith("!")           # True

# 拼接和重复
s + " Again."             # 'Hello, World! Again.'
"Hi" * 3                  # 'HiHiHi'

# f-string
name = "Alice"
age = 30
f"{name} is {age} years old."  # 'Alice is 30 years old.'

这些操作不会修改原始字符串(因为字符串是不可变的);它们会返回新的字符串。


Back

x-ai/grok-4.1-fast

Donate