Python教程 - 字符串常用方法

Python 教程 - 字符串中已经认识了字符串 String 的基本用法,这篇文章会整理出字符串的常用方法。

常用操作方法

下面整理了字符串常用的操作方法

方法 说明
str(x) 转换与创建字符串
+ 拼接字符串
重复字符串
str[] 获取字符
len(str) 获取字符串长度
str.split(x) 根据 x 拆分字符串
str.join(iter) 将列表拼接成字符串
str.replace(x, y, n) 将字符串中的 x 替换为 y,n 为要替换的数量,可不填 (表示全部替换)
str.strip() 去除字符串开头或结尾的某些字符
str.capitalize() 将字符串首字母变成大写
str.casefold()、str.lower() 将字符串全部转成小写
str.upper() 将字符串全部转成大写
str.title() 将字符串全部转成标题 (每个单词首字母大写)
str.swapcase() 将字符串的大小写反转
str.count(sub, start, end) 计算某段文本在字符串中出现的次数 (start、end 为范围,可不填)
str.index(sub, start, end) 寻找某段文本在字符串中出现的位置 (start、end 为范围,可不填)
str.format 格式化字符串,参考.format
str.encode(encoding='utf-8', errors='strict') 字符串编码

常用判断方法

下面整理了字符串常用的判断方法,这些方法使用后会返回 True 和 False。

方法 说明
sub in str 判断字符串中是否存在某段文本,返回 True 或 False。
str.isalnum() 判断字符串中是否都是英文字母或数字(不能包含空格或符号),返回 True 或 False。
str.isalpha() 判断字符串中是否都是英文字母(不能包含数字、空格或符号),返回 True 或 False。
str.isdigit() 判断字符串中是否都是数字 (不能包含英文、空白或符号),返回 True 或 False
str.islower() 判断字符串中是否都是小写英文字母,返回 True 或 False
str.isupper() 判断字符串中是否都是大写英文字母,返回 True 或 False
str.istitle() 判断字符串中是否为标题 (每个单词首字母大写),返回 True 或 False

str(x)

使用str(x)可以将 x 转换成字符串类型。

scss 复制代码
a = str(123)
print(a)   # 123 ( 字符串类型,不是数字 )

拼接字符串

使用可以将不同的字符串拼接在一起。

ini 复制代码
a = 'abc'
b = '123'
print(a + b)   # abc123

重复字符串

使用可以将同一个字符串重复指定的次数。

ini 复制代码
a = 'abc'
print(a*3)

str[]

使用str[]可以取出字符串中的某些字符。

scss 复制代码
a = '0123456789abcdef'
print(a[0])       # 0 ( 第一个字符 )
print(a[3])       # 3 ( 第四个字符 )
print(a[-1])      # f ( 最后一个字符 )
print(a[:])       # 0123456789abcdef ( 取出全部字符 )
print(a[5:])      # 56789abcdef ( 从 5 开始到结束 )
print(a[:5])      # 01234 ( 从 0 开始到第 4 个 ( 5-1 ) )
print(a[5:10])    # 56789 ( 从 5 开始到第 9 个 ( 10-1 ) )
print(a[5:-3])    # 56789abc ( 从 5 开始到倒数第 4 个 ( -3-1 ) )
print(a[5:10:2])  # 579 ( 从 5 开始到第 9 个,中间略过 2 个 )

len(str)

使用len(str)可以获取字符串长度 (有几个字符)。

ini 复制代码
a = 'hello world'
print(len(a))    # 11

str.split(x)

使用str.split(x)可以根据 x 字符拆分字符串,使字符串变成列表形式。

scss 复制代码
a = 'hello world, I am oxxo, how are you?'
b = a.split(',') # 以逗号,进行拆分
c = a.split(' ') # 以空白字符 进行拆分
d = a.split()    # 如果不指定分隔符号,自动以空白字符进行拆分
print(b)         # ['hello world', ' I am oxxo', ' how are you?']
print(c)         # ['hello', 'world,', 'I', 'am', 'oxxo,', 'how', 'are', 'you?']
print(d)         # ['hello', 'world,', 'I', 'am', 'oxxo,', 'how', 'are', 'you?']

str.join(iter)

使用str.join(iter)可以将原本的字符串,拼接指定的列表,变成新的字符串。

ini 复制代码
a = ['hello world', 'I am oxxo', 'how are you?']
b = ', '.join(a)  # 使用逗号,进行拼接
print(b)  # hello world, I am oxxo, how are you?

str.replace(x, y, n)

使用str.replace(x, y, n)可以将字符串中的 x 替换为 y,n 为要替换的数量,可不填 (表示全部替换)

ini 复制代码
a = 'hello world, lol'
b = a.replace('l','XXX')
c = a.replace('l','XXX',2)
print(b)  # heXXXXXXo worXXXd, XXXoXXX ( 所有的 l 都被换成 XXX )
print(c)  # heXXXXXXo world, lol ( 前两个 l 被换成 XXX )

str.strip()

使用str.strip()可以去除字符串开头或结尾的某些字符。

ini 复制代码
a = '  hello!!'
b = a.strip()
c = a.strip('!')
d = a.lstrip()
e = a.rstrip()
print(b) # hello!!
print(c) #   hello
print(d) # hello!!    使用 lstrip() 函数可以只去除左边
print(e) #   hello!!  使用 rstrip() 函数可以只去除右边

下面的例子,会去除开头与结尾指定的字符

ini 复制代码
s = '@!$##$#ABCDE%#$#%#$'
a = s.strip('!@#$%^&*(')
print(a)  # ABCDE

str.capitalize()

使用str.capitalize()将字符串的首字母变成大写。

css 复制代码
a = 'hello world, i am oxxo!'
b = a.capitalize()
print(b)    # Hello world, i am oxxo!

str.casefold()、str.lower()

使用str.casefold()str.lower()可以将字符串全部转成小写,str.casefold() 更会将一些其他语系的小写字母作转换。

ini 复制代码
a = 'Hello World, I am OXXO!'
b = a.casefold()
c = a.lower()
print(b)    # hello world, i am oxxo!
print(c)    # hello world, i am oxxo!

str.upper()

使用str.upper()可以将字符串全部转成大写。

css 复制代码
a = 'Hello World, I am OXXO!'
b = a.upper()
print(b)    # HELLO WORLD, I AM OXXO!

str.title()

使用str.title()可以将字符串全部转成标题 (每个单词首字母大写)

css 复制代码
a = 'Hello world, I am OXXO! How are you?'
b = a.title()
print(b)    # Hello World, I Am Oxxo! How Are You?

str.swapcase()

使用str.swapcase()可以将字符串的大小写反转。

css 复制代码
a = 'Hello world, I am OXXO!'
b = a.swapcase()
print(b)   # hELLO WORLD, i AM oxxo!

str.count(sub, start, end)

使用str.count(sub, start, end)可以计算某段文在字符串中出现的次数 (start、end 为范围,可不填)。

ini 复制代码
a = 'Hello world, I am OXXO!'
b = a.count('o')
c = a.count('o', 1, 5)
print(b)     # 2
print(c)     # 1

str.index(sub, start, end)

使用str.index(sub, start, end)可以寻找某段文本在字符串中出现的位置 (start、end 为范围,可不填)。

ini 复制代码
a = 'Hello world, I am OXXO!'
b = a.index('w')
print(b)     # 6

str.encode(encoding='utf-8', errors='strict')

使用 str.encode(encoding='utf-8', errors='strict')可以针对字符串进行编码。

ini 复制代码
a = 'Hello world, 喔哈!'
b = a.encode(encoding='utf-8', errors='strict')
c = a.encode(encoding='BIG5', errors='strict')
print(b)    # b'Hello world, \xe5\x93\x88\xe5\x93\x88\xef\xbc\x81'
print(c)    # b'Hello world, \xab\xa2\xab\xa2\xa1I'

sub in str

使用sub in str可以判断字符串中是否存在某段文本,返回 True 或 False (也可使用 not in 判断是否不存在)。

bash 复制代码
a = 'Hello world!'
print('wo' in a)      # True
print('ok' not in a)  # True

str.isalnum()

使用str.isalnum()可以判断字符串中是否都是英文字母或数字 (不能包含空白或符号),返回 True 或 False。

ini 复制代码
a = 'Helloworld123'
b = 'Helloworld123!!'
c = 'Hello world'
print(a.isalnum())   # True
print(b.isalnum())   # False ( 包含惊叹号 )
print(c.isalnum())   # False ( 包含空白 )

str.isalpha()

使用str.isalpha()可以判断字符串中是否都是英文字母 (不能包含数字、空白或符号),返回 True 或 False。

ini 复制代码
a = 'Helloworld'
b = 'Helloworld123'
c = 'Hello world'
print(a.isalpha())   # True
print(b.isalpha())   # False ( 包含数字 )
print(c.isalpha())   # Fasle ( 包含空白 )

str.isdigit()

使用str.isdigit()可以判断字符串中是否都是数字 (不能包含英文、空白或符号),返回 True 或 False。

ini 复制代码
a = '12345'
b = 'Hello123'
c = '1 2 3'
print(a.isdigit())   # True
print(b.isdigit())   # False  ( 包含英文 )
print(c.isdigit())   # Fasle  ( 包含空白 )

str.islower()

使用str.islower()可以判断字符串中是否都是小写英文字母 (忽略数字和符号),返回 True 或 False。

ini 复制代码
a = 'hello world 123'
b = 'Hello World 123'
print(a.islower())    # True
print(b.islower())    # False ( H 和 W 是大写 )

str.isupper()

使用str.isupper()可以判断字符串中是否都是大写英文字母 (忽略数字和符号),返回 True 或 False。

ini 复制代码
a = 'HELLO 123'
b = 'Hello 123'
print(a.isupper())    # True
print(b.isupper())    # False

str.istitle()

使用str.istitle()可以判断字符串中是否为标题 (每个单词首字母大写),返回 True 或 False。

ini 复制代码
a = 'Hello World I Am Oxxo 123!!'
b = 'Hello World I Am OXXO 123!!'
c = 'Hello world, I am OXXO 123!!'
print(a.istitle())    # True
print(b.istitle())    # False ( OXXO 全都大写 )
print(c.istitle())    # False ( world 和 am 首字母没有大写 )
相关推荐
不写八个9 分钟前
Python办公自动化教程(005):Word添加段落
开发语言·python·word
_.Switch27 分钟前
Python机器学习框架介绍和入门案例:Scikit-learn、TensorFlow与Keras、PyTorch
python·机器学习·架构·tensorflow·keras·scikit-learn
赵荏苒39 分钟前
Python小白之Pandas1
开发语言·python
计算机学姐1 小时前
基于SpringBoot+Vue的高校运动会管理系统
java·vue.js·spring boot·后端·mysql·intellij-idea·mybatis
一眼万里*e1 小时前
fish-speech语音大模型本地部署
python·flask·大模型
结衣结衣.2 小时前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习
程序员陆通2 小时前
Spring Boot RESTful API开发教程
spring boot·后端·restful
茫茫人海一粒沙2 小时前
Python 代码编写规范
开发语言·python
林浩2332 小时前
Python——异常处理机制
python
数据分析螺丝钉2 小时前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试