Python字符串基础操作与常用方法详解

云舒
云舒
发布时间:2026-10-12 | 3人浏览过
原创

本文系统讲解Python字符串的基础操作,涵盖单双三引号赋值、基于索引的字符串截取技巧,以及strip、lower、upper等常用处理函数。重点解析format格式化语法及find、index等查找方法的区别,帮助开发者掌握字符串处理核心技能。

字符串赋值

在Python中,字符串可以通过单引号(' ')、双引号(" ")、三单引号(''' ''')或三双引号(""" """)来定义。

使用单引号将字符串赋值给变量

a = 'hello world'
print('>> 单引号字符串赋值给变量')
print(a)
--Console-----
>> 单引号字符串赋值给变量
hello world

使用双引号将字符串赋值给变量

b = "hello world"
print('>> 双引号字符串赋值给变量')
print(b)
--Console-----
>> 双引号字符串赋值给变量
hello world

使用三引号将多行字符串赋值给变量

c = '''
双引号字符串赋
值给变量
'''
print('>> 三引号字符串赋值给变量')
print(c)
--Console-----
>> 三引号字符串赋值给变量
双引号字符串赋
值给变量

字符串截取

字符串支持类似列表的索引访问方式,使用方括号【[]】即可获取指定位置的字符。

截取指定索引位置的单个字符

d = ' 我爱你中国,我 爱你世界,i Love China  'd_1 = d[2] #指定索引为1的字符串,ps:在编程语言中,索引基本师基于0开始的print('>> 截取指定位置的字符')print(d_1)--Console----->> 截取指定位置的字符爱d = ' 我爱你中国,我 爱你世界,i Love China  '
d_1 = d[2] #指定索引为1的字符串,ps:在编程语言中,索引基本师基于0开始的
print('>> 截取指定位置的字符')
print(d_1)
--Console-----
>> 截取指定位置的字符
爱

获取指定索引位置之后的所有字符

d = ' 我爱你中国,我 爱你世界,i Love China  '
d_2 = d[2:]
print('>> 截取指定位置之后的所有字符')
print(d_2)
--Console-----
>> 截取指定位置之后的所有字符
爱你中国,我 爱你世界,i Love China  

获取指定索引位置之前的所有字符

d = ' 我爱你中国,我 爱你世界,i Love China  '
d_3 = d[:2]
print('>> 截取指定位置之前的所有字符')
print(d_3)
--Console-----
>> 截取指定位置之前的所有字符
 我

获取字符串中的所有字符

d = ' 我爱你中国,我 爱你世界,i Love China  '
d_4 = d[::]
print('>> 获取所有的字符')
print(d_4)
--Console-----
>> 获取所有的字符
 我爱你中国,我 爱你世界,i Love China 

使用负数【-】表示倒数位置,获取指定倒数位置的字符

使用负数【-】表示倒数位置,获取指定倒数位置的字符

d = ' 我爱你中国,我 爱你世界,i Love China  '
d_5 = d[-3]
print('>>获取指定倒数位置的字符,用【-】来进行表示')
print(d_5)
--Console-----
>>获取指定倒数位置的字符,用【-】来进行表示
a

获取指定位置之前(不含该位置)的所有字符

d = ' 我爱你中国,我 爱你世界,i Love China  '
d_6 = d[:-2]
print('>获取指定位置倒数之前的字符')
print(d_6)
--Console-----
>获取指定位置倒数之前的字符
 我爱你中国,我 爱你世界,i Love China

获取两个指定位置之间的字符子串

d = ' 我爱你中国,我 爱你世界,i Love China  '
d_7 = d[4:8]
d_8 = d[-8:-1]
print('>>获取两个位置之间的字符')
print(d_7)
print(d_8)
--Console-----
>>获取两个位置之间的字符
中国,我
 China 

字符串基础使用方法

strip()

#删除开头和结尾的空格的空白字符
d = ' 我爱你中国,我 爱你世界,i Love China  '
d_8 = d.strip()
print('>>strip(): 删除开头和结尾的空格的空白字符 ')
print(d_8)
--Console-----
>>strip(): 删除开头和结尾的空格的空白字符 
我爱你中国,我 爱你世界,i Love China

lstrip()

#删除开头的空白字符
d = ' 我爱你中国,我 爱你世界,i Love China  '
d_9 = d.lstrip()
print('>>lstrip(): 删除开头的空白字符 ')
print(d_9)
--Console-----
>>lstrip(): 删除开头的空白字符 
我爱你中国,我 爱你世界,i Love China 

rstrip()

用于删除字符串结尾的空白字符

d = ' 我爱你中国,我 爱你世界,i Love China  '
d_10 = d.rstrip()
print('>>rstrip(): 删除结尾的空白字符')
print(d_10)
--Console-----
>>rstrip(): 删除结尾的空白字符
 我爱你中国,我 爱你世界,i Love China

lower()

返回转换为小写形式的字符串

d = ' 我爱你中国,我 爱你世界,i Love China  '
d_11 = d.lower()
print('>>lower(): 返回小写的字符串')
print(d_11)
--Console-----
>>lower(): 返回小写的字符串
 我爱你中国,我 爱你世界,i love china 

upper()

返回转换为大写形式的字符串

d = ' 我爱你中国,我 爱你世界,i Love China  '
d_12 = d.upper()
print('>>upper(): 返回大写的字符串')
print(d_12)
--Console-----
>>upper(): 返回大写的字符串
 我爱你中国,我 爱你世界,I LOVE CHINA 

capitalize()

返回首字母大写的字符串

d_13 = 'i love China'
d_13_1 = d_13.capitalize()
print('>>  capitalize(): 返回首字符大写的字符串')
print(d_13_1)
--Console-----
>>  capitalize(): 返回首字符大写的字符串
I love china

title()

返回标题格式字符串,将每个单词的首字母转换为大写

d_13 = 'i love China'
d_14 = d_13.title()
print('>> title(): 返回标题形式的字符串,转换为大写')
print(d_14)
--Console-----
>> title(): 返回标题形式的字符串,转换为大写
I Love China

index()

#获取指定字符的索引
d_13 = 'i love China'
d_15 = d_13.index('i') #如果存在多个则返回第一个索引
print('>> index():获取指定字符的索引')
print(d_15)
print('>> index(): 根据指定字符及位置区间进去获取')
d_16 = d_13.index('i',5,10) #如果超出字符串长度,则会报错,如果查询不到则返回为空
print(d_16)
--Console-----
>> index():获取指定字符的索引
0
>> index(): 根据指定字符及位置区间进去获取
9
#获取指定字符的索引
d_13 = 'i love China'
d_15 = d_13.index('i') #如果存在多个则返回第一个索引
print('>> index():获取指定字符的索引')
print(d_15)
print('>> index(): 根据指定字符及位置区间进去获取')
d_16 = d_13.index('i',5,10) #如果超出字符串长度,则会报错,如果查询不到则返回为空
print(d_16)
--Console-----
>> index():获取指定字符的索引
0
>> index(): 根据指定字符及位置区间进去获取
9

rindex()

#与index方法操作相似,不过返回的是最后一个匹配的字符串的索引号
d_13 = 'i love China'
d_15 = d_13.rindex('i') #如果存在多个则返回第一个索引
print('>> rindex():获取指定字符的索引')
print(d_15)
--Console-----
>> rindex():获取指定字符的索引
9

split()

根据指定的分隔符对字符串进行分割,返回一个列表类型

print('>> split(): 根据指定的分隔符进行分割,返回列表类型')d_13 = 'i love China'd_17 = d_13.split(' ')print(d_17)--Console----->> split(): 根据指定的分隔符进行分割,返回列表类型['i', 'love', 'China']print('>> split(): 根据指定的分隔符进行分割,返回列表类型')
d_13 = 'i love China'
d_17 = d_13.split(' ')
print(d_17)
--Console-----
>> split(): 根据指定的分隔符进行分割,返回列表类型
['i', 'love', 'China']

replace()

执行字符串替换操作

print('>> replace():字符串的替换')
'''
replace(x,y) x为需要替换的字符,y替换的字符
'''
d_13 = 'i love China'
d_18 = d_13.replace(' ','/')
print(d_18)
--Console-----
>> replace():字符串的替换
i/love/China

count()

返回指定子字符串在原文中出现的次数

print('>>count(): 返回指定字符串出现的次数 ')
d_13 = 'i love China'
d_20 = d_13.count('i')
print(d_20)
--Console-----
>>count(): 返回指定字符串出现的次数 
2

find(): 查找指定子字符串首次出现的索引

find方法与index方法功能基本相同,唯一区别在于:当查找不到指定字符串时,index方法会抛出报错,而find方法返回-1。

print('>> find(): 查找字符串')
d_13 = 'i love China'
d_21 = d_13.find('i')
print(d_21)
--Console-----
>> find(): 查找字符串
0

rfind(): 查找指定子字符串最后出现的索引

rfind方法与find方法基本相同,区别在于返回的是子字符串最后出现的位置;如果没有匹配到,则返回-1。

print('>> rfind() 查找字符串')
d_13 = 'i love China'
d_21 = d_13.rfind('i')
print(d_21)
--Console-----
>> rfind() 查找字符串
9

center()

使用指定字符(默认为空格)进行居中对齐

d_22 = 'china'
d_22_1 = d_22.center(50)
d_22_2 = d_22.center(50,'*')
print('>>center():使用指定的字符【默认空格】,进行居中对齐 ')
print(d_22_1)
print(d_22_2)
--Console-----
>>center():使用指定的字符【默认空格】,进行居中对齐 
                      china                       
**********************china***********************

endswith()

判断字符串是否以指定字符结尾,若是则返回True,否则返回False

d_23 = 'i love china'
d_23_1 = d_23.endswith('china')
print('>>endswith(): 判断是字符串以指定的字符结尾,则返回为True,否则返回False')
print(d_23_1)
--Console-----
>>endswith(): 判断是字符串以指定的字符结尾,则返回为True,否则返回False
True

startswith()

判断字符串是否以指定字符开头,若是则返回True,否则返回False

d_24 = 'i love china'
d_24_1 = d_24.startswith('i')
print('>> startswith(): 判断字符串以指定的字符进行开头,则返回为True,否则返回False')
print(d_24_1)
--Console-----
>> startswith(): 判断字符串以指定的字符进行开头,则返回为True,否则返回False
True

isalnum()

判断字符串中的所有字符是否均为字母或数字,若是则返回True,否则返回False

d_25 = 'all the world'
d_26 = 'alla1'
print('>>isalnum(): 判断字符串中的所有字符都是字母数字,则返回为True,否则返回False')
d_25_1 = d_25.isalnum()
d_26_1 = d_26.isalnum()
print(d_25_1)
print(d_26_1)
--Console-----
>>isalnum(): 判断字符串中的所有字符都是字母数字,则返回为True,否则返回False
False
True

isalpha()

判断字符串非空且所有字符均为字母,若是则返回True,否则返回False

d_25 = 'all the world'
d_26 = 'alla1'
print('>>isalnum(): 判断字符串中的所有字符都是字母数字,则返回为True,否则返回False')
d_25_1 = d_25.isalnum()
d_26_1 = d_26.isalnum()
print(d_25_1)
print(d_26_1)
--Console-----
>>isalnum(): 判断字符串中的所有字符都是字母数字,则返回为True,否则返回False
False
True

isdigit()

判断字符串是否仅包含数字字符,若是则返回True,否则返回False

d_27 = 'alll'
print('>>isalpha():判断字符不能为空,并且所有字符都是字母,则返回为True,否则返回False')
d_27_1 = d_27.isalpha()
print(d_27_1)
--Console-----
>>isalpha():判断字符不能为空,并且所有字符都是字母,则返回为True,否则返回False
True

isnumeric()

判断字符串是否仅包含数字字符(含中文数字等),若是则返回True,否则返回False

d_30 = '1230'
d_31 = '12.0ssss'
print('>> isnumeric: 判断是否只包含数字字符')
d_30_1 = d_30.isdigit()
d_31_1 = d_31.isdigit()
print(d_30_1)
print(d_31_1)
--Console-----
>> isnumeric: 判断是否只包含数字字符
True
False

istitle()

判断字符串是否符合标题格式(每个单词首字母大写),若是则返回True,否则返回False

d_32 = 'Hello'
d_33 = 'hello'
print('>> istitle: 判断字符串是否是title格式,则返回为True,否则返回为False')
d_32_1 = d_32.istitle()
d_33_1 = d_33.istitle()
print(d_32_1)
print(d_33_1)
--Console-----
>> istitle: 判断字符串是否是title格式,则返回为True,否则返回为False
True
False

islower()

判断字符串是否全部为小写,若是则返回True,否则返回False

d_33 = 'hello'
d_34 = 'Hello'
print('>> islower(): 判断是否小写')
d_33_1 = d_33.islower()
d_34_1 = d_34.islower()
print(d_33_1)
print(d_34_1)
--Console-----
>> islower(): 判断是否小写
True
False

isupper()

判断字符串是否全部为大写,若是则返回True,否则返回False

d_33 = 'HELLO'
d_34 = 'Hello'
print('>> isupper(): 判断是否大写')
d_33_1 = d_33.isupper()
d_34_1 = d_34.isupper()
print(d_33_1)
print(d_34_1)
--Console-----
>> isupper(): 判断是否大写
True
False

isspace()

判断字符串是否仅包含空格字符,若是则返回True,否则返回False

d_33 = '    'd_34 = 'He l lo'print('>> isspace(): 判断是否只包含空格')d_33_1 = d_33.isspace()d_34_1 = d_34.isspace()print(d_33_1)print(d_34_1)--Console----->> isspace(): 判断是否只包含空格TrueFalsed_33 = '    '
d_34 = 'He l lo'
print('>> isspace(): 判断是否只包含空格')
d_33_1 = d_33.isspace()
d_34_1 = d_34.isspace()
print(d_33_1)
print(d_34_1)
--Console-----
>> isspace(): 判断是否只包含空格
True
False

len()

#获取字符串的长度
x = '1222222222'
x_len = len(x)
print('>>len(): 获取字符串的长度')
print(x_len)
--Console-----
>>len(): 获取字符串的长度
10

join()

将一个有序列表中的元素,按指定的分隔字符合并成一个新的字符串

x = ['a','b','c']
x_join ='-'.join(x)
print('>>  join():将一个有序的列表,按指定的字符进行合并成一个新的字符串 ')
print(x_join)
--Console-----
>>  join():将一个有序的列表,按指定的字符进行合并成一个新的字符串 
a-b-c

max()

获取字符串中ASCII码值最大的字符

x = 'abcdfefdga'
x_max = max(x)
print('>> manx(): 获取字符串最大的字母')
print(x_max)
--Console-----
>> manx(): 获取字符串最大的字母
g

min()

获取字符串中ASCII码值最小的字符

x = 'abcdfefdga'
x_min = min(x)
print('>> min(): 获取字符串最大的字母')
print(x_min)
--Console-----
>> min(): 获取字符串最大的字母
a

zfill()

返回指定长度的字符串,原字符串右对齐,不足部分在前面补0

x = '12'
x_zfill = x.zfill(50)
print('>>zfill(): 返回指定长度的字符串,原字符串向右对其,前面补充0')
print(x_zfill)
--Console-----
>>zfill(): 返回指定长度的字符串,原字符串向右对其,前面补充0
00000000000000000000000000000000000000000000000012

format()

字符串格式化

y = 'abd'
x_format = '{0}'.format(y)
print('>>format(): 格式化字符串')
print(x_format)
--Console-----
>>format(): 格式化字符串
abd

‘{:.2f}’.format():保留两位小数的浮点数格式化

#保留两位小数
x = '{:.2f}'.format(34.1255555)
print(x)
--Console-----
34.13

‘{:+.2f}’.format():带符号的两位小数浮点数格式化

#保留两位小数
x = '{:.2f}'.format(34.1255555)
print(x)
--Console-----
34.13

‘{:.0f}’.format():不保留小数位的浮点数格式化

#不保留小数
x =  '{:.0f}'.format(34.1255555)
print(x)
--Console-----
34

‘{:x>2d}’.format():右对齐,不足补指定字符x的整数格式化

#左边填充,5 则为长度,x为填充字符,支持自定义
x =  '{:x>5d}'.format(23)
print(x)
--Console-----
xxx23

‘{:x<2d}’.format():左对齐,不足补指定字符x的整数格式化

#右边填充,5 则为长度,x为填充字符,支持自定义
x =  '{:x<5d}'.format(23)
print(x)
--Console-----
23xxx

‘{:,}’.format():带千位分隔符的数字格式化

#以逗号作为分隔符,常用于金额千分位的表达
x = '{:,}'.format(255555555555)
print(x)
--Console-----
255,555,555,555

‘{:.2%}’.format():百分比格式,保留两位小数

#百分比格式
x = '{:.2%}'.format(0.25)
print(x)
--Console-----
25.00%

‘{:>10d}’.format():右对齐,宽度为10的整数格式化

#右对齐.10则为长度
x = '{:>10d}'.format(12)
print(x)
--Console-----
        12

‘{:<10d}’.format():左对齐,宽度为10的整数格式化

#左对齐.10则为长度
x = '{:<10d}'.format(12)
print(x)
--Console-----
12        

‘{:^10d}’.format():居中对齐,宽度为10的整数格式化

#中间对齐.10则为长度
x = '{:^10d}'.format(12)
print(x)
--Console-----
    12    

‘{:b}’, ‘{:d}’, ‘{:o}’, ‘{:x}’:分别用于二进制、十进制、八进制和十六进制的转换

x = '{:b}'.format(11) #转换2进制
print(x)
y = '{:d}'.format(11) #转换10进制
print(y)
z = '{:o}'.format(11) #转换8进制
print(z)
e = '{:x}'.format(11) #转换16进制
print(e)
--Console-----
1011
11
13
b

检查字符串

d_13 = 'i love China'
print('>>检查字符串')
if 'love' in d_13:
    print('匹配')
else:
    print('不匹配')
--Console-----
>>检查字符串
匹配

字符串的串联

d_13 = 'i love China'
d_19 = d_13+d_13
print('>> 字符串的串联')
print(d_19)
--Console-----
>> 字符串的串联
i love Chinai love China

字符串的遍历

'''字符串遍历可以使用for循环进行遍历'''
d_13 = 'i love China'
print('>>字符串遍历可以使用for循环进行遍历')
for ins in d_13:
    print(ins)
--Console-----
>>字符串遍历可以使用for循环进行遍历
i
l
o
v
e
C
h
i
n
a

总结

本文到此结束,希望能为读者提供帮助,欢迎持续关注本站获取更多技术内容!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表