Python字符串对象自带一批方法,用来查找、替换、拆分、拼接以及判断字符类别。调用后都会得到新的字符串(或列表、整数等返回值),原字符串本身不会被改掉。

先看几个常用调用

s = "  Hello World  "
print(s.strip())         # Hello World
print(s.lower())         #   hello world
print(s.upper())         #   HELLO WORLD
print(s.replace("World", "Python"))  #   Hello Python
print(s.split())         # ['Hello', 'World']

大小写转换

s = "hello world"
print(s.upper())       # HELLO WORLD
print("ABC".lower())   # abc
print(s.title())       # Hello World,每个单词首字母大写
print(s.capitalize())  # Hello world,只有首字母大写
print("AbC".swapcase())  # aBc,大小写互换

查找与判断

find 找不到时返回 -1,index 找不到会抛异常,从右边找用 rfind

s = "I love Python, Python is great"

print(s.find("Python"))     # 7,第一个出现位置,找不到返回 -1
print(s.rfind("Python"))    # 15,从右找
print(s.index("Python"))    # 7,找不到会抛异常(和 find 区别在这)
print(s.startswith("I"))    # True
print(s.endswith("great"))  # True
print(s.count("Python"))    # 2

去空白与对齐

s = "   hi   "
print(repr(s.strip()))    # 'hi',去两头
print(repr(s.lstrip()))   # 'hi   ',去左
print(repr(s.rstrip()))   # '   hi',去右

print("42".zfill(5))      # 00042,左边补零到 5 位
print("hi".center(9, "-"))  # ---hi----,居中
print("hi".ljust(6, "*"))   # hi****,左对齐填充

拆分与拼接

csv = "apple,banana,orange"
print(csv.split(","))          # ['apple', 'banana', 'orange']
print("a b c".split())         # ['a', 'b', 'c'],默认按空白
print("apple,banana".split(",", 1))  # ['apple', 'banana'],最多拆1次

words = ["2024", "01", "15"]
print("-".join(words))         # 2024-01-15,join 是拼接

判断类型(is 系列)

print("123".isdigit())     # True
print("12a".isdigit())     # False
print("abc".isalpha())     # True
print("abc1".isalnum())    # True,字母或数字
print("   ".isspace())     # True,全空白
print("Hello World".istitle())  # True

用 is 系列校验输入

判断用户输入是不是纯数字,是很常见的写法:

s = input("输入一个整数: ")
if s.isdigit():
    print(f"你输入了数字 {s}")
else:
    print("那不是纯数字")

常用方法总表

方法作用
strip() / lstrip() / rstrip()去首尾 / 左 / 右空白
upper() / lower() / title()转大写 / 小写 / 首字母大写
replace(old, new)替换子串
find) / rfind()查找子串位置(找不到 -1)
startswith() / endswith()判断开头 / 结尾
count()统计出现次数
split() / join()拆成列表 / 拼成字符串
isalpha() / isdigit() / isalnum() / isspace()字符类别判断
zfill() / center()补零 / 居中