Python_字符串检测与压缩

  1 '''
  2 center()、ljust()、rjust(),返回指定宽度的新字符串,原字符串居中、左对齐或右对齐出现在新字符串中,
  3 如果指定宽度大于字符串长度,则使用指定的字符(默认为空格进行填充)。
  4 '''
  5 print('Hello world!'.center(20))    #居中对齐,以空格进行填充
  6 #     Hello world!
  7 print('Hello world!'.center(20,'='))   #居中对齐,以字符=进行填充
  8 # ====Hello world!====
  9 print('Hello world!'.ljust(20,'='))    #左对齐
 10 # Hello world!========
 11 print('Hello world!'.rjust(20,'='))    #右对齐
 12 # ========Hello world!
 13 
 14 '''
 15 zfill()返回指定宽度的字符串,在左侧以字符0进行填充
 16 '''
 17 print('abc'.zfill(5))   #在左侧填充数字字符0
 18 # 00abc
 19 print('abc'.zfill(2))   #指定宽度小于字符串长度时,返回字符串本身
 20 # abc
 21 
 22 '''
 23 isalnum()   检测字符串是否为数字或字母
 24 isalpha()   检测字符串是否只由字母组成
 25 isdigit()   检测字符串是否只由数字组成
 26 isdecimal() 检测字符串是否只包含十进制字符
 27 isnumeric() 检测字符串是否只由数字组成
 28 isspace()   检测字符串是否只由空格组成
 29 isupper()   检测字符串中所有的字母是否都为大写
 30 islower()   检测字符串是否由小写字母组成
 31 '''
 32 print('1234abcd'.isalnum()) #检测字符串是否为数字或字母
 33 # True
 34 print('!!'.isalpha()) #全部为英文字母时返回True
 35 # False
 36 print('abcd'.isalpha())
 37 # True
 38 print('1234.0'.isdigit())   #检测字符串是否由数字组成
 39 # False
 40 print('1234'.isdigit())
 41 # True
 42 print(''.isnumeric())  #isnumeric()方法支持汉字数字
 43 # True
 44 print('9'.isnumeric())
 45 # True
 46 print(''.isdigit())
 47 # False
 48 print('10'.isdecimal())     #只包含十进制字符
 49 # True
 50 print('ⅣⅢⅩ'.isdecimal())
 51 # False
 52 print('ⅣⅢⅩ'.isdigit())
 53 # False
 54 print('ⅣⅢⅩ'.isnumeric())   #支持罗马数字
 55 # True
 56 
 57 '''
 58 Python内置函数也可以对字符串进行操作
 59 '''
 60 x = 'Hello world.'
 61 print(len(x))   #字符串长度
 62 # 12
 63 print(max(x))   #最大字符
 64 # w
 65 print(min(x))   #最小字符
 66 # ' '
 67 print(list(zip(x,x)))  #zip()也可以作用于字符串
 68 # [('H', 'H'), ('e', 'e'), ('l', 'l'), ('l', 'l'), ('o', 'o'), (' ', ' '), ('w', 'w'), ('o', 'o'), ('r', 'r'), ('l', 'l'), ('d', 'd'), ('.', '.')]
 69 
 70 '''
 71 切片也适用于字符串,但仅限于读取其中的元素,不支持字符串修改
 72 '''
 73 print('Explicit is better than implicit.'[:8])
 74 # Explicit
 75 print('Explicit is better than implicit.'[9:23])
 76 # is better than
 77 
 78 '''
 79 Python标准库zlib中提供compress()和decompres()函数可以用于数据的压缩和解压缩,
 80 在压缩字符串之前需要先编码为字节串
 81 '''
 82 import zlib
 83 x = 'Python是我认为最好的一门编程语言,使用广泛'.encode()
 84 print(len(x))
 85 # 60
 86 y = zlib.compress(x)
 87 print(len(y))   #对于重复度比较小的信息,压缩比小
 88 # 71
 89 x = ('Python是我认为最好的一门编程语言,使用广泛'*3).encode()
 90 print(len(x))
 91 # 180
 92 y=zlib.compress(x)  #信息重复度越高,压缩比越大
 93 print(len(y))
 94 # 77
 95 z = zlib.decompress(y)
 96 print(len(z))
 97 # 180
 98 print(z.decode())
 99 # Python是我认为最好的一门编程语言,使用广泛Python是我认为最好的一门编程语言,使用广泛Python是我认为最好的一门编程语言,使用广泛
100 x=['zWrite']*8
101 y=str(x).encode()
102 print(len(y))
103 # 80
104 z=zlib.compress(y)
105 print(len(z))
106 # 22
107 print(zlib.decompress(z).decode())
108 # ['zWrite', 'zWrite', 'zWrite', 'zWrite', 'zWrite', 'zWrite', 'zWrite', 'zWrite']
原文地址:https://www.cnblogs.com/cmnz/p/6961686.html