python数据类型之str用法

1、首字母大写

语法:S.capitalize() -> str

title = "today is a good day"
title_ca = title.capitalize()
print(title_ca)

结果:today is a good day

2、大写转小写

1 语法:S.casefold() -> str
2 
3 title = "TODAY is a GOOD day"
4 title_ca = title.casefold()
5 print(title_ca)

结果:Today is a good day

3、字符串居中

c = 'kong'

ret = c.center(10,'*')
print(ret)

结果:***kong***

 4、字符串子串数量统计

S.count(sub[, start[, end]]) -> int

title = "today is a good day"
title_ca = title.count('y',1,5)
print(title_ca)

结果:1

5、中文转UTF-8

S.encode(encoding='utf-8', errors='strict') -> bytes

zw = '孔扎根'
ut = zw.encode()
print(ut)

结果:b'xe7xa9xbaxe6x89x8exe6xa0xb9'

6、字符串结束判断

S.endswith(suffix[, start[, end]]) -> bool

title = "TODAY is a GOOD day"
title_ca = title.endswith('day')
print(title_ca)

结果:True

7、TAB转空格

S.expandtabs(tabsize=8) -> str
#默认是一个TAB转8个空格
title = "TODAY	is	a	GOOD	day"
title_ca = title.expandtabs()
print(title_ca)

结果:TODAY   is      a       GOOD    day

8、查找字符串的位置

 S.find(sub[, start[, end]]) -> int

title = "TODAY	is	a	GOOD	day"
title_ca = title.find('s')
print(title_ca)

结果:7

9、字符串格式化

S.format(*args, **kwargs) -> str
#可传入元组或字典
title = "{}	is	a	{day_type}	day"
title_ca = title.format('TODAY',day_type='GOOD')
print(title_ca)

结果:TODAY    is    a    GOOD    day

10、字符串格式化,从字典输入(format_map)

S.format_map(mapping) -> str
#输入参数为字典,循环读字典中的列表
maping_name = {
    'name':['alex','join'],
    'age':[18,19]
}

for x in range(2):
    print('my name is {},and i is {} old'.format(maping_name['name'][x],maping_name['age'][x]))

结果:
my name is alex,and i is 18 old
my name is join,and i is 19 old

11、字符串的索引位置

S.index(sub[, start[, end]]) -> int
#查找Y的索引位置,从0开始数
title = "TODAY	is	a	GOOD	day"
title_ca = title.index('Y')
print(title_ca)

结果:4

12、字符串中至少有一个数字

S.isalnum() -> bool
#字符串不能有空格,否则失败
title = "22TODAY"
title_ca = title.isalnum()
print(title_ca)

结果:True

13、字符串中至少有一个字母

 S.isalpha() -> bool
#字符串不能有空格或TAB键
title = "22TODAY"
title_ca = title.isalnum()
print(title_ca)

结果:True

14、字符串是否为数值

num = "1" #unioncode
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
True
True
True

num = ""#全角
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
True
True
True

num = b"1"#byte
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
True
AttributeError: 'bytes' object has no attribute 'isdecimal'
AttributeError: 'bytes' object has no attribute 'isnumeric'

num = "IV"#罗马字符
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
False
False
False

num = ""#汉字
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
False
False
True

支持的字符: isdigit:支持 unioncode,全角,
byte,汉字 isdecimal:支持 unioncode,全角, isnumeric:支持 unioncode,全角,汉字
报错: isdigit不会报错,后两种在byte判断时会报错

 15、判断字符串是否为有效标识符(可做为函数名称)

#S.isidentifier() -> bool
t_code = 'test'
print(t_code.isidentifier())
结果:返回True
t_code = '23test'
print(t_code.isidentifier())
结果:返回False

16、判断字符串是否全小写

#S.islower() -> bool
t_code = 'kongzhagen'
print(t_code.islower())
结果:返回True
t_code = 'kongzHagen'
print(t_code.islower())
结果:返回False

17、判断字符串是否全整型数字

#S.isnumeric() -> bool
t_code = '123'
print(t_code.isnumeric())
结果:返回True
t_code = '123d'
print(t_code.isnumeric())
结果:返回False
t_code = '123.123'
print(t_code.isnumeric())
结果:返回False

18、判断所有字符是否可打印

#S.isprintable() -> bool
t_code = '123KKK'
print(t_code.isprintable())
返回:True
t_code = ''
print(t_code.isprintable())
返回:True
t_code = 'KKK
	'
print(t_code.isprintable())
返回:False

19、判断字符中是否全为空格

#S.isspace() -> bool
t_code = '   '
print(t_code.isspace())
结果:返回True
t_code = '123 KKK'
print(t_code.isspace())
结果:返回False

20、判断字符串是否为标题格式(首字母大写)

#S.istitle() -> bool
t_code = 'Today Is A Good Day'
print(t_code.istitle())
结果:True
t_code = 'Today Is A Good day'
print(t_code.istitle())
结果:False
t_code = 'TODAY IS'
print(t_code.istitle())
结果:False

21、判断字符串是否全大写

#S.isupper() -> bool
t_code = 'Today Is A Good day'
print(t_code.isupper())
结果:False
t_code = 'TODAY IS'
print(t_code.isupper())
结果:True

22、字符串连接

#S.join(iterable) -> str
t_code = 'Today Is A Good Day'
t1_code = '.'.join(t_code)
print(t1_code)
结果:T.o.d.a.y. .I.s. .A. .G.o.o.d. .D.a.y

23、左对齐,达不到指定长度,右则填充

#S.ljust(width[, fillchar]) -> str
t_code = 'Today Is A Good Day'
print(t_code.ljust(22,'*'))
结果:Today Is A Good Day***

24、转小写

#S.lower() -> str
t_code = 'Today Is A Good Day'
print(t_code.lower())
结果:today is a good day

25、左边去除指定字符,默认为空格

# S.lstrip([chars]) -> str
t_code = 'Today Is A Good Day'
print(t_code.lstrip('T'))
结果:oday Is A Good Day
t_code = '  Today Is A Good Day'
print(t_code.lstrip())
结果:Today Is A Good Day

26、

maketrans

27、partition

按指定的字符拆分字符串,分头、分隔串、尾,未找到指定的分隔符,头返回自己,后面两个返回空
#S.partition(sep) -> (head, sep, tail) t_code = 'TodayIs A Good Day' print(t_code.partition('a')) 结果:('Tod', 'a', 'yIs A Good Day') print(t_code.partition('P')) 结果:('TodayIs A Good Day', '', '')

28、replace:字符串替换

将老字符串替换为新字符串,可指定替换次数
#S.replace(old, new[, count]) -> str t_code = 'TodayIs A Good Day,To today' print(t_code.replace('T','M',2)) 结果:ModayIs A Good Day,Mo today

29、rfind:返回查询到的字符串的最大索引

#S.rfind(sub[, start[, end]]) -> int
t_code = 'TodayIs A Good Day,To today'
print(t_code.rfind('d'))
结果:24

30、rindex:类似rfind,但如果没找到会报错

#S.rindex(sub[, start[, end]]) -> int
t_code = 'TodayIs A Good Day,To today'
print(t_code.rindex('p'))
结果:

Traceback (most recent call last):
File "C:/51py/day1/study.py", line 90, in <module>
print(t_code.rindex('p'))
ValueError: substring not found

 

31、rjust:右对齐,左侧填充字符

#S.rjust(width[, fillchar]) -> str
t_code = 'Today'
print(t_code.rjust(10,'*'))
结果:*****Today

32、rpartition:类似partition,如果未找到字符串,则空值在左边

#S.rpartition(sep) -> (head, sep, tail)
t_code = 'Today is a good day'
print(t_code.rpartition('isa'))
结果:('', '', 'Today is a good day')

33、rsplit:分割字符串,从右边开始

#S.rsplit(sep=None, maxsplit=-1) -> list of strings
t_code = 'Today is a good day'
print(t_code.rsplit('o',1))
结果:['Today is a go', 'd day']

34、rstrip:右边去空格

#S.rstrip([chars]) -> str
t_code = '  Today is a good day  '
print(t_code.rstrip())
结果:  Today is a good day

35、splitlines:方法返回一个字符串的所有行列表,可选包括换行符的列表(如果num提供,则为true)

#S.splitlines([keepends]) -> list of strings
t_code = 'Today
 is
 a
 good
 day'
print(t_code.splitlines())
print(t_code.splitlines(0))
print(t_code.splitlines(1))
结果:
['Today', ' is', ' a', ' good', ' day']
['Today', ' is', ' a', ' good', ' day']
['Today
', ' is
', ' a
', ' good
', ' day']

36、startswith:如果字符串以指定的字符为前缀,则返回true,否则返回false

#S.startswith(prefix[, start[, end]]) -> bool
t_code = 'Today
 is
 a
 good
 day'
print(t_code.startswith('Today'))
结果:True

37、strip:去除字符串前后的空格

#S.strip([chars]) -> str
t_code = ' Today
 is
 a
 good
 day '
print(t_code.strip())  
结果:
Today
 is
 a
 good
 day

38、swapcase:大小写互转

#S.swapcase() -> str
t_code = ' Today Is a Good Day '
print(t_code.swapcase())
结果: tODAY iS A gOOD dAY 

39、title:返回的字符串为title格式,首字母大写

#S.title() -> str
t_code = ' today is a Good Day '
print(t_code.title())
结果:Today Is A Good Day 

40、maketrans:用于创建字符映射的转换表,两个参数为长度相等的字符串

#B.maketrans(frm, to) -> translation table
intab = "aeiou"
outab = "1234k"
trantab = t_code.maketrans(intab,outab)
print(trantab)
结果:{97: 49, 111: 52, 117: 107, 101: 50, 105: 51}

41、translate:根据参数table给出的表转换字符中的字符

# S.translate(table) -> str
t_code = ' today is a Good Day '
trantab = {97:49}
print(t_code.translate(trantab))
结果: tod1y is 1 Good D1y 

42、ord与chr是配对函数

>>> chr(65)
'A'
>>> ord('A')
65

43、upper:将字符串转为大写

#S.upper() -> str
t_code = ' today is a Good Day '
print(t_code.upper())
结果:TODAY IS A GOOD DAY 

44、zfill:数字填零

#S.zfill(width) -> str
t_code = '123'
print(t_code.zfill(5))
结果:00123

45、汇总

str = 'https://www.baidu. com234'
# print(str.capitalize())  # 第一个字母大写
# print(str.count('w'))  # 字符在字符串中出现的次数
# print(str.endswith('com'))  # 字符串是否以com结尾
# print(str.expandtabs(tabsize=2))  # 字符串中的tab转为两个空格
# print(str.find('bai'))  # 返回字符串中bai的索引
# print(str.rfind('bai'))  # 返回字符串中bai的索引,从右边找
# print(str.index('bai'))  # 返回字符串中bai的索引,未找到会报错
# print(str.rindex())  # 返回字符串中bai的索引,未找到会报错(从右边找)
# print(str.isalnum())  # 如果所有字符都是数字或字母,则返回True
# print(str.isalpha())  # 如果所有字符都是字母,则返回True
# print(str.isnumeric())  # 如果所有字符都是数字,则返回T
# print(str.isdecimal())  # 可解释为十进制数,则返回True
# print(str.isdigit())  # 可解释为数字,则返回True
# print(str.islower())  # 字符串中的字母都小写,则返回True(可以有其它字符)
# print(str.isupper())  # 字符串中的字母都大写,则返回True(可以有其它字符)
# print(str.isspace())  # 字符串中全是空格,则返回True
# print(str.istitle())  # 如果字符串是标题化的,则返回True(每个单词首字母大写,其它小写)
# print(str.ljust(100))  # 字符串左对齐,长度100
# print(str.rjust(100))  # 字符串右对齐,长度100
# print(str.lower())  # 所有字符转小写
# print(str.lstrip())  # 去掉字符串左边的空格
print str.replace('t','2',2)  # 将p 替换为2,替换2次
print str.rfind('o')  # 从右边查找第一个o所在的位置
print str.rindex('o')  # 从右边查找第一个o所在的位置的索引
print str.partition('du')  # 从左边找到第一个du,并以之分隔字符串,返回列表
print str.rstrip()  # 去掉右边的空格
print str.split('w',2) # 以w为分隔符,切分字符串
print str.splitlines()  # 以行做为分隔符
print str.startswith('http')  # 是否以http开头
print str.swapcase()  # 翻转大小写
print str.title()  # 将string标题化,所有单词首字母大写,其它小写
print str.upper() # 所有字母大写
print str.zfill(150)  # 返回150个字符,原字符串右对齐,前面填充0
原文地址:https://www.cnblogs.com/kongzhagen/p/5426064.html