0
点赞
收藏
分享

微信扫一扫

Python 序列 - 字符串

Separes 2021-09-29 阅读 68

一. 常用函数

ord() 接收单字符字符串,返回Unicode代码。

>> ord('a'), ord('A')
(97, 65)
>> ord('中'), ord('国')
(20013, 22269)

chr() ord的反向应用,接收Unicode代码,返回字符串。

>> chr(97), chr(65)
('a', 'A')
>> chr(20013), chr(22269)
('中', '国')

hex() 得到十进制数对应的十六进制。

>> hex(127), hex(128)
('0x7f', '0x80')

bin() 得到十进制数对应的二进制。

>> bin(127), bin(128)
('0b1111111', '0b10000000')

oct() 得到十进制数对应的八进制。

>> oct(127), oct(128)
('0o177', '0o200')

int() 数值型字符串转换为整数。

>> hex(int('127')), hex(int('128'))
('0x7f', '0x80')

float() 数值型字符串转换为浮点数。

len() 获取字符串长度。

>> len('china'), len('中国')
(5, 2)

max() 获取字符串中最大值。

>> max('china'), max('中国')
('n', '国')

min() 获取字符串中最小值。

>> min('china'), min('中国')
('a', '中')

二. 常用方法

find()rfind() 查找子字符串在字符串中首次出现的位置,没找到则返回 -1。

>> my_str = '我和我亲爱的祖国'
>> my_str.find('我'), my_str.rfind('我'), my_str.find('日')
(0, 2, -1)

index()rindex() 同find()方法,但在没找到时会触发 ValueError 异常。

>> my_str.index('我'), my_str.rindex('我')
(0, 2)
>> my_str.index('日')
ValueError: substring not found

strip()lstrip()rstrip():去掉字符串两端指定的字符串,得到新的字符串。

>> s = '\r\n    \t abc \r\n    \t end.\r\n    \t '
>> s.strip()
'abc \r\n    \t end.'

count() 统计字符串中,子字符串出现的次数。

>> '上海自来水来自海上'.count('上')
2

upper() 将字母全部转换为大写,返回一个新字符串。

>> 'mia'.upper() == 'MIA'
True

lower() 将字母全部转换为小写,返回一个新字符串。

>> assert 'MIA'.lower() == 'mia'

title():字符串中每个单词的首字母大写,其余小写。

>> 'mia'.title()
'Mia'

replace():在源字符串中替换指定部分,返回新字符串;指定字符串未找到,则返回原字符串。

>>> my_str = 'a,b,c,d'
>>> my_str.replace(',', ' ')
'a b c d'

capitalize() 字符串首字母大写,其余小写。

>>> 'python hello world'.capitalize()
'Python hello world'

swapcase() 把字符串中的大小写字母互换,返回一个新字符串。

>>> 'HELLO python'.swapcase()
'hello PYTHON'

center() 将字符串居中,左右使用指定字符串填充,默认为空格。

>>> 'hello python'.title().center(20, '*')
'****Hello Python****'

三. 返回值为布尔值的方法

startwith(prefix[,start,end]) 判断字符串是否以 prefix 开头。
endswith(suffix[,start,end]) 判断字符串是否以 suffix 结尾。

>>> assert 'Python'.startswith('P') and 'Python'.endswith('n')
>>>

islower() 判断字母是否全部为小写,不理会其它字符;如果字符串不包含字母,则返回 False
isupper() 判断字母是否全部为大写,不理会其它字符;如果字符串不包含字母,则返回 False

>>> assert 'python'.islower() and 'python'.upper().isupper()
>>>

istitle():判断字符串中每个单词的首字母是否全部为大写;如果字符串不包含字母,则返回 false

>>> 'Hello Python'.istitle()
True
>>> 'Hello python'.istitle()
False

isalpha():判断字符串是否只包含文字字符,中文为合法字符。
isdigit():判断字符串是否只包含数字。

>>> assert 'Python入门基础'.isalpha()
>>> assert '12308'.isdigit()
>>>

isspace():判断字符串是否只包含 空格,\t,\n

>>> assert '\r\n    \t'.isspace()
>>> 
举报

相关推荐

0 条评论