python-字符串常用方法

字符串常用方法:

1 Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置  

1 name = 'xiaoming'
2 print(name.count('i')) # 从第0位开始统计到最后
3 print(name.count('i',2,4)) # 从第2位开始统计,到第4位结束
4 print(name.count('i',2,6)) # 从第2位开始统计,到第6位结束

结果:

2
0
1

 

2 Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与

 python find()方法一样,只不过如果str不在 string中会报一个异常。

str1 = "this is string example....wow!!!";
str2 = "exam";
 
print str1.index(str2);
print str1.index(str2, 10);
print str1.index(str2, 40);

结果:
15
15
Traceback (most recent call last):
  File "test.py", line 8, in 
  print str1.index(str2, 40);
ValueError: substring not found

 

3 Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串,注意:默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

tr = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split(); # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个

结果:

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

 

4 python strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列,注意:该方法只能删除开头或者结尾的字符,不能删除删除中间部分的字符:

4.1 去除首尾字符:

str1 = "00003210Runoob012300000";
print(str1.strip('0'));# 去除首尾字符0
结果:3210Runoob0123

str2 = " Runoob "; #去除首位空格
print(str2.strip())
结果:Runoob

4.2 去除首尾字符序列

str3 = '123adc123121'
print(str3.strip('12'))# 去除首尾字符序列12
结果:3abc123

 

5 Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

 

names = ['1','2','3','4','5']
s2 = '123'
result = ''.join(names)
result='@'.join(names)
print(result)
print(type(result))

seq = ("a", "b", "c"); # 字符串序列
print('-'.join(seq))

str = 'abcd'
print(','.join(str))

结果:
1@2@3@4@5
<class 'str'>
a-b-c
a,b,c,d

 

 

 

6 Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

tr = "this is string example....wow!!!";
print (str.startswith( 'this' ))
print (str.startswith( 'is', 2, 4 ))
print (str.startswith( 'this', 2, 4 ))
结果:
True
True
False

 

 

7 Python endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。

str = "this is string example....wow!!!";
 
suffix = "wow!!!";
print str.endswith(suffix);
print str.endswith(suffix,20);
 
suffix = "is";
print str.endswith(suffix, 2, 4);
print str.endswith(suffix, 2, 6);

结果:
True
True
True
False

 

8 Python upper() 方法将字符串中的小写字母转为大写字母。

str = "this is string example....wow!!!";
print (str.upper())

结果:
THIS IS STRING EXAMPLE....WOW!!!

 

9 Python lower() 方法转换字符串中所有大写字符为小写。

str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.lower();

结果:
this is string example....wow!!!

 

10 Python zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。

str = "this is string example....wow!!!";
print str.zfill(40);
print str.zfill(50);

结果:
00000000this is string example....wow!!!
000000000000000000this is string example....wow!!!

 

11 Python enumerate() 用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

# 方法一:默认下标从0开始
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
for s in enumerate(seasons):
    print(s)

# 结果:

(0, 'Spring')
(1, 'Summer')
(2, 'Fall')
(3, 'Winter')


# 方法二:‘3’代表下标从3开始
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
for s in enumerate(seasons,3):
    print(s)

# 结果:

(3, 'Spring')
(4, 'Summer')
(5, 'Fall')
(6, 'Winter')

 12 Python ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

 1 while True:
 2     try:
 3         s = input("输入字符串")
 4         while len(s) > 8:
 5             print("s[:8]",s[:8]) # 切片去前8位字符
 6             s = s[8:] # 切皮去8位之后的所有字符
 7         print("s.ljust",s.ljust(8, "0")) # 字符串长度8位,不够8位,用0补全
 8     except:
 9         break
10 
11 # 结果
12 输入字符串:1234567890987654321
13 s[:8] 12345678
14 s[:8] 90987654
15 s.ljust 32100000

 13 Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。

 1 info = 'abca'
 2 print(info.find('a'))      # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
 3 #输出
 4 0
 5 print(info.find('a', 1))   # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3
 6 # 输出
 7 3
 8 print(info.find('3'))      # 查找不到返回-1
 9 #输出
10 -1

14 Python round()方法返回浮点数x的四舍五入值。

1 print "round(80.23456, 2) : ", round(80.23456, 2)
2 print "round(100.000056, 3) : ", round(100.000056, 3)
3 print "round(-100.000056, 3) : ", round(-100.000056, 3)
4 
5 #输出
6 round(80.23456, 2) :  80.23
7 round(100.000056, 3) :  100.0
8 round(-100.000056, 3) :  -100.0

15 Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

 1 '''
 2 参数
 3 old -- 将被替换的子字符串。
 4 new -- 新字符串,用于替换old子字符串。
 5 max -- 可选字符串, 替换不超过 max 次
 6 
 7 返回值
 8 返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。
 9 '''
10 
11 str = "this is string example....wow!!! this is really string";
12 print str.replace("is", "was");
13 print str.replace("is", "was", 3);
14 
15 # 输出
16 
17 thwas was string example....wow!!! thwas was really string
18 thwas was string example....wow!!! thwas is really string

 

posted @ 2019-08-09 23:33  术科术  阅读(267)  评论(0编辑  收藏  举报