python学习4

字符串

字符串常用方法

find()、rfind()、index()、rindex()、count()

find()和rfind()方法分别用来查找一个字符串在另一个字符串指定范围(默认是整个字符串)中首次和最后一次出现的位置,如果不存在则返回-1;

index()和rindex()方法用来返回一个字符串在另一个字符串指定范围中首次和最后一次出现的位置,如果不存在则抛出异常;

count()方法用来返回一个字符串在当前字符串中出现的次数。

>>> s="apple,peach,banana,peach,pear"
>>> s.find("peach")
6
>>> s.find("peach",7)
19
>>> s.find("peach",7,20)
-1
>>> s.rfind('p')
25
>>> s.index('p')
1
>>> s.index('pe')
6
>>> s.index('pear')
25
>>> s.index('ppp')
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    s.index('ppp')
ValueError: substring not found
>>> s.count('p')
5
>>> s.count('pp')
1
>>> s.count('ppp')
0

 split()、rsplit()、partition()、rpartition()

split()和rsplit()方法分别用来以指定字符为分隔符,把当前字符串从左往右或从右往左分隔成多个字符串,并返回包含分隔结果的列表

partition()和rpartition()用来以指定字符串为分隔符将原字符串分隔为3部分,即分隔符前的字符串、分隔符字符串、分隔符后的字符串,如果指定的分隔符不在原字符串中,则返回原字符串和两个空字符串

>>> s = "apple,peach,banana,pear"
>>> s.split(",")
["apple", "peach", "banana", "pear"]
>>> s.partition(',')
('apple', ',', 'peach,banana,pear')
>>> s.rpartition(',')
('apple,peach,banana', ',', 'pear')
>>> s.rpartition('banana')
('apple,peach,', 'banana', ',pear')
>>> s = "2017-10-31"
>>> t = s.split("-")
>>> print(t)
['2017', '10', '31']
>>> print(list(map(int, t)))
[2017, 10, 31]

对于split()和rsplit()方法,如果不指定分隔符,则字符串中的任何空白符号(空格、换行符、制表符等)都将被认为是分隔符,并删除切分结果中的空字符串。

>>> s = 'hello world \n\n My name is Dong   '
>>> s.split()
['hello', 'world', 'My', 'name', 'is', 'Dong']
>>> s = '\n\nhello world \n\n\n My name is Dong   '
>>> s.split()
['hello', 'world', 'My', 'name', 'is', 'Dong']
>>> s = '\n\nhello\t\t world \n\n\n My name\t is Dong   '
>>> s.split()
['hello', 'world', 'My', 'name', 'is', 'Dong']

然而,明确传递参数指定split()使用的分隔符时,情况是不一样的,会保留切分得到的空字符串。

>>> 'a,,,bb,,ccc'.split(',')       #每个逗号都被作为独立的分隔符
['a', '', '', 'bb', '', 'ccc']
>>> 'a\t\t\tbb\t\tccc'.split('\t') #每个制表符都被作为独立的分隔符
['a', '', '', 'bb', '', 'ccc']
>>> 'a\t\t\tbb\t\tccc'.split()     #连续多个制表符被作为一个分隔符
['a', 'bb', 'ccc']

split()和rsplit()方法还允许指定最大分割次数。

字符串连接join()

>>> li = ["apple", "peach", "banana", "pear"]
>>> ','.join(li)
'apple,peach,banana,pear'
>>> '.'.join(li)
'apple.peach.banana.pear'
>>> '::'.join(li)
'apple::peach::banana::pear'

lower()、upper()、capitalize()、title()、swapcase()

>>> s = "What is Your Name?"
>>> s.lower()                   #返回小写字符串
'what is your name?'
>>> s.upper()                   #返回大写字符串
'WHAT IS YOUR NAME?'
>>> s.capitalize()              #字符串首字符大写
'What is your name?'
>>> s.title()                   #每个单词的首字母大写
'What Is Your Name?'
>>> s.swapcase()                #大小写互换
'wHAT IS yOUR nAME?'

查找替换replace(),类似于Word中的“全部替换”功能。

>>> words = ('测试', '非法', '暴力', '话')
>>> text = '这句话里含有非法内容'
>>> for word in words:
    if word in text:
        text = text.replace(word, '***')		
>>> text
'这句***里含有***内容'

字符串对象的maketrans()方法用来生成字符映射表,而translate()方法用来根据映射表中定义的对应关系转换字符串并替换其中的字符,使用这两个方法的组合可以同时处理多个字符。

#创建映射表,将字符"abcdef123"一一对应地转换为"uvwxyz@#$"
>>> table = ''.maketrans('abcdef123', 'uvwxyz@#$')
>>> s = "Python is a great programming language. I like it!"
>>> s.translate(table)          #按映射表进行替换
'Python is u gryut progrumming lunguugy. I liky it!'

strip()、rstrip()、lstrip()

>>> s = " abc  "
>>> s.strip()                             #删除空白字符
'abc'
>>> '\n\nhello world   \n\n'.strip()      #删除空白字符
'hello world'
>>> "aaaassddf".strip("a")                #删除指定字符
'ssddf'
>>> "aaaassddf".strip("af")
'ssdd'
>>> "aaaassddfaaa".rstrip("a")            #删除字符串右端指定字符
'aaaassddf'
>>> "aaaassddfaaa".lstrip("a")            #删除字符串左端指定字符
'ssddfaaa'

这三个方法的参数指定的字符串并不作为一个整体对待,而是在原字符串的两侧、右侧、左侧删除参数字符串中包含的所有字符,一层一层地从外往里扒。

>>> 'aabbccddeeeffg'.strip('af')  #字母f不在字符串两侧,所以不删除
'bbccddeeeffg'
>>> 'aabbccddeeeffg'.strip('gaf')
'bbccddeee'
>>> 'aabbccddeeeffg'.strip('gaef')
'bbccdd'
>>> 'aabbccddeeeffg'.strip('gbaef')
'ccdd'
>>> 'aabbccddeeeffg'.strip('gbaefcd')
''

成员判断,关键字in

>>> "a" in "abcde"     #测试一个字符中是否存在于另一个字符串中
True
>>> 'ab' in 'abcde'
True
>>> 'ac' in 'abcde'    #关键字in左边的字符串作为一个整体对待
False
>>> "j" in "abcde"
False

Python字符串支持与整数的乘法运算,表示序列重复,也就是字符串内容的重复,得到新字符串。

s.startswith(t)、s.endswith(t),判断字符串是否以指定字符串开始或结束

>>> s = 'Beautiful is better than ugly.'
>>> s.startswith('Be')           #检测整个字符串
True
>>> s.startswith('Be', 5)        #指定检测范围起始位置
False
>>> s.startswith('Be', 0, 5)     #指定检测范围起始和结束位置
True
>>> import os
>>> [filename for filename in os.listdir(r'c:\\')
     if filename.endswith(('.bmp','.jpg','.gif'))]

center()、ljust()、rjust(),返回指定宽度的新字符串,原字符串居中、左对齐或右对齐出现在新字符串中,如果指定宽度大于字符串长度,则使用指定的字符(默认为空格)进行填充。

>>> 'Hello world!'.center(20)        #居中对齐,以空格进行填充
'    Hello world!    '
>>> 'Hello world!'.center(20, '=')   #居中对齐,以字符=进行填充
'====Hello world!===='
>>> 'Hello world!'.ljust(20, '=')    #左对齐
'Hello world!========'
>>> 'Hello world!'.rjust(20, '=')    #右对齐
'========Hello world!'

isalnum()、isalpha()、isdigit()、isdecimal()、isnumeric()、isspace()、isupper()、islower(),用来测试字符串是否为数字或字母、是否为字母、是否为数字字符、是否为空白字符、是否为大写字母以及是否为小写字母。

>>> '1234abcd'.isalnum()
True
>>> '1234abcd'.isalpha()         #全部为英文字母时返回True
False
>>> '1234abcd'.isdigit()         #全部为数字时返回True
False
>>> 'abcd'.isalpha()
True
>>> '1234.0'.isdigit()
False
>>> '1234'.isdigit()
True
>>> '九'.isnumeric()             #isnumeric()方法支持汉字数字
True
>>> '九'.isdigit()
False
>>> '九'.isdecimal()
False
>>> 'ⅣⅢⅩ'.isdecimal()
False
>>> 'ⅣⅢⅩ'.isdigit()
False
>>> 'ⅣⅢⅩ'.isnumeric()         #支持罗马数字
True

切片也适用于字符串,但仅限于读取其中的元素,不支持字符串修改。

>>> 'Explicit is better than implicit.'[:8]
'Explicit'
>>> 'Explicit is better than implicit.'[9:23]
'is better than'

Pytho标准库zlib中提供的compress()和decompress()函数可以用于字节串的压缩和解压缩。

>>> import zlib
>>> x = 'Python程序设计系列图书,董付国编著'.encode()
>>> len(x)
48
>>> len(zlib.compress(x))
59

字符串常量

Python标准库string中定义数字字符、标点符号、英文字母、大写字母、小写字母等常量。

>>> import string
>>> string.digits
'0123456789'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

应用:密码随机生成

>>> import string
>>> characters = string.digits + string.ascii_letters
>>> import random
>>> ''.join([random.choice(characters) for i in range(8)])
'J5Cuofhy'
>>> ''.join([random.choice(characters) for i in range(10)])
'RkHA3K3tNl'
>>> ''.join([random.choice(characters) for i in range(16)])
'zSabpGltJ0X4CCjh'
>>> ''.join(random.choices(characters, k=12))
'4NvBiOqy0Ej1'

正则表达式

正则表达式使用某种预定义的模式去匹配一类具有共同特征的字符串,主要用于处理字符串,可以快速、准确地完成复杂的查找、替换等处理要求,在文本编辑与处理、网页爬虫之类的场合中有重要应用。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值