使用字符串

本文详细介绍了Python中字符串的各种常用方法,包括find()、join()、lower()、title()、replace()、split()、strip()及translate()等。通过具体实例展示了每个方法的功能和使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 基本操作
所有标准的序列操作(索引、分片、乘法、判断成员资格、求长度、取最小值、最大值)都适用与字符串,字符串不允许改变

  • 字符串方法

  • find() 
在一个字符串中查找子字符串,它返回子串中所在位置左端索引,如果找到返回-1
格式:
.find(self,sub,__start,__end)
1
1
 
1
.find(self,sub,__start,__end)
s = 'great,beautiful,contry,Python'
print s.find('bea')     #返回6,表示第6个索引位置起找到了
print s.find('cc')      
print s.find('python')  #未发现返回-1
print 'bea'in(s)        #in也判断有没有,返回的是布尔值,


#指定起点和终点搜索范围的,但是范围包括_start,但不包括_end(Python中一般都这样)
print s.find('bea',3)      
print s.find('bea',3,7)
print s.find('bea',3,8)
print s.find('bea',3,10)

#输出
6
-1
-1
6
18
18
 
1
s = 'great,beautiful,contry,Python'
2
print s.find('bea')     #返回6,表示第6个索引位置起找到了
3
print s.find('cc')      
4
print s.find('python')  #未发现返回-1
5
print 'bea'in(s)        #in也判断有没有,返回的是布尔值,
6
7
8
#指定起点和终点搜索范围的,但是范围包括_start,但不包括_end(Python中一般都这样)
9
print s.find('bea',3)      
10
print s.find('bea',3,7)
11
print s.find('bea',3,8)
12
print s.find('bea',3,10)
13
14
#输出
15
6
16
-1
17
-1
18
6
注:
字符串中的 find 方法并不是返回布尔值,如返回0,则表示索引0位置

  • join() 
join()方法是非常重要的字符串方法,它是split()的逆方法,用于连接序列中的元素, 注意,被连接的元素必须都是字符串
# seq = [1,2,3]
# sqe = '+'
# sqe.join(seq)   #join()只能用于字符串的连接,所以报错

a =['1','2','3']
b ='+'
print b.join(a)
#输出
1+2+3
9
9
 
1
# seq = [1,2,3]
2
# sqe = '+'
3
# sqe.join(seq)   #join()只能用于字符串的连接,所以报错
4
5
a =['1','2','3']
6
b ='+'
7
print b.join(a)
8
#输出
9
1+2+3

  • lower()
lower()方法返回字符串小写字母版
name = 'a'
names = ('A','B','C')   #列表无法直接使用 lower()方法,这里用str()转化为字符串
names = str(names)
if(name in names.lower()):
    print 'fount it'

name = 'A'
names = ('a','b','c')
if(name.lower() in names):
    print 'fount it'

#输出
#上述两者都输出“found it”
13
13
 
1
name = 'a'
2
names = ('A','B','C')   #列表无法直接使用 lower()方法,这里用str()转化为字符串
3
names = str(names)
4
if(name in names.lower()):
5
    print 'fount it'
6
7
name = 'A'
8
names = ('a','b','c')
9
if(name.lower() in names):
10
    print 'fount it'
11
12
#输出
13
#上述两者都输出“found it”

  • title()
会讲字符串转换为标题--也就是所有的单词的首字母大写,而其他字母小写
print "that's all folks".title()
#输出
That'S All Folks      #有点问题,那个s不应该大写


#还可以使用 string 模块中的 capword()函数
import string         
print string.capwords("that's all folks")
8
8
 
1
print "that's all folks".title()
2
#输出
3
That'S All Folks      #有点问题,那个s不应该大写
4
5
6
#还可以使用 string 模块中的 capword()函数
7
import string         
8
print string.capwords("that's all folks")

  • replace()
replace() 方法返回某个字符串的所有匹配项均被替换之后得到的字符串
print "that's all folks".replace('all','a')  #第一个参数是要被替代的字符,第二个新字符
#输出
that's a folks
3
3
 
1
print "that's all folks".replace('all','a')  #第一个参数是要被替代的字符,第二个新字符
2
#输出
3
that's a folks

  • split()
split分隔,join的逆方法,将字符串分割成序列
如果不提供任何的分隔符,那么程序会把所有的空格作为分隔符(空格、制表、换行等)
print '1+2+3+4+5'.split('+')
print '/usr/bin/env'.split('/')
#输出
['1', '2', '3', '4', '5']
['', 'usr', 'bin', 'env']
5
5
 
1
print '1+2+3+4+5'.split('+')
2
print '/usr/bin/env'.split('/')
3
#输出
4
['1', '2', '3', '4', '5']
5
['', 'usr', 'bin', 'env']
string.rsplit([sep[,maxsplit ]])同split,但是在使用maxsplit是从右向左进行计数
string.split([sep[,maxsplit ]])返回字符串中所有单词的列表,使用 sep 作为分隔符(如果未特别指出以空格切分单词),可使用 maxsplit 指定最大切分数

  • strip()
strip() 方法返回去除两侧(不包括内部)空格或者指定的字符
它和 lower() 方法一起使用可以很方便的对比输入的和存储的值 
name = 'a '  # ' a '前后都有空格,所以结果为wrong,可以使用 strip()去除两侧的空格
names = ('a','b','c')
names = str(names)
if(name.strip() in names.lower()):  # strip() 移除两侧的空格
    print 'fount it'
else:
    print 'wrong'


print "**that's **all*!* folks *!*  ***".strip('**! ')
#输出
that's **all*!* folks  #只会移除两侧的字符,内部的不会被移除
13
13
 
1
name = 'a '  # ' a '前后都有空格,所以结果为wrong,可以使用 strip()去除两侧的空格
2
names = ('a','b','c')
3
names = str(names)
4
if(name.strip() in names.lower()):  # strip() 移除两侧的空格
5
    print 'fount it'
6
else:
7
    print 'wrong'
8
9
10
print "**that's **all*!* folks *!*  ***".strip('**! ')
11
#输出
12
that's **all*!* folks  #只会移除两侧的字符,内部的不会被移除
13
string.lstrip([chars])返回一个字符串副本,其中所有的chars(默认为空白字符、比如空格、tab和换行符)都被字符串开始去除
string.rstrip([chars])返回一个字符串副本,其中所有的chars(默认为空白字符,比如空格、tab和换行符)都被从字符串结束处去除

  • translate()
translate() 方法和 replace() 方法一样,可以替换字符串中的某些部分,但是和前者不同的是,translate() 方法只处理单个字符,它的优势在于可以同时进行多个替换,有时效率比  replace() 效率高
常与 maketrans() 一起使用
# translate有一个可选的参数deletchars,表示指定需要删除的字符,
# 格式:.translate(self,table,deletchars)
# table:翻译表,通过 string 模块中 maketrans()方法而来
# deletechars:字符串中要过滤的字符列表


import string

s = 'abcdefg-1234567'
table = string.maketrans('', '')        # 没有映射,实际上就是按原始字符保留,看下面用到translate中时的效果
print s.translate(table)                # 输出abcdefg-1234567
print s.translate(table, 'abc123')      # 输出defg-4567 可以看到删除了字符abc123

#输出
abcdefg-1234567
defg-4567


# 下面再看有字符映射时的效果
table = string.maketrans('abc', 'ABC')  # 用于translate中时的效果如下
print s.translate(table)                # 输出ABCdefg-1234567 就是将abc映射为大写的ABC,前提是abc如果被保留下来了
print s.translate(table, 'ab123')       # 输出Cdefg-4567 先把s中的ab123去除了,
                                        # 然后在保留下来的字符中应用table中指定的字符映射关系映射:c -> C

    
x
25
 
1
# translate有一个可选的参数deletchars,表示指定需要删除的字符,
2
# 格式:.translate(self,table,deletchars)
3
# table:翻译表,通过 string 模块中 maketrans()方法而来
4
# deletechars:字符串中要过滤的字符列表
5
6
7
import string
8
9
s = 'abcdefg-1234567'
10
table = string.maketrans('', '')        # 没有映射,实际上就是按原始字符保留,看下面用到translate中时的效果
11
print s.translate(table)                # 输出abcdefg-1234567
12
print s.translate(table, 'abc123')      # 输出defg-4567 可以看到删除了字符abc123
13
14
#输出
15
abcdefg-1234567
16
defg-4567
17
18
19
# 下面再看有字符映射时的效果
20
table = string.maketrans('abc', 'ABC')  # 用于translate中时的效果如下
21
print s.translate(table)                # 输出ABCdefg-1234567 就是将abc映射为大写的ABC,前提是abc如果被保留下来了
22
print s.translate(table, 'ab123')       # 输出Cdefg-4567 先把s中的ab123去除了,
23
                                        # 然后在保留下来的字符中应用table中指定的字符映射关系映射:c -> C
24
25
    


转载于:https://my.oschina.net/u/1785519/blog/1582425

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值