Python 字符串常用方法
·
Python 字符串常用方法
字符串是不可变对象,所有方法不会修改原字符串,只会返回新字符串。s = "hello Python"
一、大小写转换
s = "Hello Python"
s.upper() # 全部大写:HELLO PYTHON
s.lower() # 全部小写:hello python
s.title() # 每个单词首字母大写:Hello Python
s.capitalize() # 仅第一个字符大写:Hello python
s.swapcase() # 大小写互换:hELLO pYTHON
二、去除空格/指定字符
text = " python "
text.strip() # 去掉左右两端空格
text.lstrip() # 去掉左边空格
text.rstrip() # 去掉右边空格
# 去除指定字符
"xxabcxx".strip("xx") # abc
三、查找与计数
s = "apple banana apple"
s.find("apple") # 返回首次出现下标,找不到返回 -1
s.index("apple") # 找不到直接报错
s.rfind("apple") # 从右往左查找
s.count("apple") # 统计子串出现次数
四、判断类方法(返回 True / False)
s.isdigit() # 是否全数字 "123"→True
s.isalpha() # 是否全字母 "abc"→True
s.isalnum() # 字母+数字混合 "a123"→True
s.isspace() # 是否全空格
s.startswith("he") # 是否以he开头
s.endswith("on") # 是否以on结尾
五、分割、合并
split 分割字符串
data = "张三,22,男"
data.split(",") # 按逗号分割成列表:["张三","22","男"]
"a b c".split() # 不传参数,自动按任意空白分割
join 拼接列表为字符串
lst = ["I", "love", "Python"]
" ".join(lst) # I love Python
"-".join(lst) # I-love-Python
六、替换
s = "java java python"
s.replace("java", "C++") # 全部替换
s.replace("java", "C++", 1) # 只替换前1个
七、对齐填充
"123".center(8, "*") # 居中:**123***
"123".ljust(8, "0") # 左对齐:12300000
"123".rjust(8, "0") # 右对齐:00000123
八、格式化
- f-string(推荐)
name = "小明"
age = 19
res = f"姓名:{name},年龄:{age}"
- format
"姓名:{},年龄:{}".format("小明", 19)
九、字符串切片(基础操作)
s = "Python"
s[0] # P
s[1:4] # yth 左闭右开
s[::-1] # 字符串反转:nohtyP
十、常用示例汇总
# 1. 去除首尾空格并转大写
txt = " hello world "
new = txt.strip().upper()
# 2. 统计单词数量
sent = "I like python python"
print(sent.count("python"))
# 3. 分割、替换、拼接
info = "苹果,香蕉,橙子"
lst = info.split(",")
lst2 = [x.replace("苹果", "葡萄") for x in lst]
res = "/".join(lst2)
更多推荐


所有评论(0)