[Python]String Methods 字符串方法

在 Python 中,字符串(str)是 不可变(immutable)对象,但提供了大量 内置字符串方法(String Methods)来进行处理,如大小写转换、查找、替换、拆分等。下面按照 常见类别系统整理 Python 字符串方法。


一、大小写转换方法

lower()

将字符串转换为小写。

s = "Hello World"
print(s.lower())

输出:

hello world

upper()

转换为大写。

s = "hello"
print(s.upper())

输出:

HELLO

title()

每个单词首字母大写。

s = "hello world"
print(s.title())

输出:

Hello World

capitalize()

字符串首字母大写。

s = "hello world"
print(s.capitalize())

输出:

Hello world

swapcase()

大小写互换。

s = "Hello World"
print(s.swapcase())

输出:

hELLO wORLD

二、查找字符串

find()

查找子字符串,返回索引。

s = "hello world"
print(s.find("world"))

输出:

6

如果不存在:

-1

index()

类似 find(),但找不到会报错。

s.index("world")

错误:

ValueError

count()

统计出现次数。

s = "banana"
print(s.count("a"))

输出:

3

startswith()

s = "hello world"
print(s.startswith("hello"))

输出:

True

endswith()

print(s.endswith("world"))

三、字符串替换

replace()

s = "hello world"
print(s.replace("world", "python"))

输出:

hello python

限制替换次数:

s.replace("a","x",2)

四、字符串分割

split()

s = "a,b,c"
print(s.split(","))

输出:

['a', 'b', 'c']

rsplit()

从右侧开始分割。

s = "a,b,c"
print(s.rsplit(",",1))

输出:

['a,b', 'c']

splitlines()

s = "a\nb\nc"
print(s.splitlines())

输出:

['a', 'b', 'c']

五、字符串连接

join()

words = ["Python","is","great"]

print(" ".join(words))

输出:

Python is great

原理:

separator.join(iterable)

六、去除字符

strip()

去除两端空格。

s = "  hello  "
print(s.strip())

输出:

hello

lstrip()

左侧去除。

s.lstrip()

rstrip()

右侧去除。

s.rstrip()

指定字符

s = "***hello***"
print(s.strip("*"))

输出:

hello

七、字符串判断方法

isalpha()

是否全部为字母。

"hello".isalpha()

True


isdigit()

"123".isdigit()

True


isalnum()

字母或数字。

"abc123".isalnum()

isspace()

"   ".isspace()

islower() / isupper()

"hello".islower()
"HELLO".isupper()

八、字符串对齐与填充

center()

"hello".center(20)

输出:

'       hello        '

ljust()

"hello".ljust(10)

rjust()

"hello".rjust(10)

zfill()

填充 0:

"42".zfill(5)

输出:

00042

九、字符串格式化

format()

"Hello {}".format("Alice")

输出:

Hello Alice

2 f-string(推荐)

name = "Alice"
print(f"Hello {name}")

十、编码与解码

encode()

s = "hello"
print(s.encode("utf-8"))

输出:

b'hello'

十一、字符串方法完整列表(常用)

方法作用
lower小写
upper大写
title标题格式
capitalize首字母大写
swapcase大小写交换
find查找
index查找
count统计
replace替换
split分割
join连接
strip去空格
startswith开头判断
endswith结尾判断
isalpha字母判断
isdigit数字判断

十二、字符串不可变特性

在 Python 中:

s = "hello"
s.upper()

不会修改原字符串:

print(s)

仍然是:

hello

必须:

s = s.upper()

✅ 总结

Python 字符串方法主要分为:

  1. 大小写转换
  2. 查找统计
  3. 替换
  4. 分割连接
  5. 去除字符
  6. 字符串判断
  7. 格式化与填充

这些方法构成了 Python 文本处理的核心工具。


如果你愿意,我可以再给你整理一个 Python字符串方法速查表(50+方法完整分类),很多高级开发者也会收藏这一份。

文章已创建 5074

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部