初学python随笔-字符串的方法总结

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
字符串方法

 我们通过dir(str)拿到了这些方法,其中我们要讲的方法是不带_下划线的,会针对每一个做个实例,并做对比

['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
 
'''
capitalize() 和 title()
两者区别 
title()返回字符串中所有单词首字母大写且其他字母小写的格式,capitalize()返回首字母大写、其他字母全部小写的新字符串。
其中像hello_word或者hello()word 使用title()也会转换成Hello_Word和Hello()Word 
'''

print('abc XY'.capitalize()) 
>>>Abc xy 
print('ab XY'.title()) 
>>>Ab Xy 


'''
lower()和upper()
两者区别
lower()返回字符串都为小写格式,upper()返回字符串都为大写格式
'''
print('abc ABC'.lower())
>>>abc abc

print('abc ABC'.upper())
>>>ABC ABC


# swapcase()  将字符串大小写转换
print('abc ABC'.swapcase())
>>>ABC abc


# isdecimal()、isdigit()、isnumeric()、isalpha()和isalnum()
'''
  isdigit()

  True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字

  False: 汉字数字

  Error: 无

  isdecimal()

  True: Unicode数字,,全角数字(双字节)

  False: 罗马数字,汉字数字

  Error: byte数字(单字节)

  isnumeric()

  True: Unicode数字,全角数字(双字节),罗马数字,汉字数字

  False: 无

  Error: byte数字(单字节)

  isalpha()

  如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False

  isalnum()

  如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回     
   False
'''

num = "1"  #unicode
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

num = "1" # 全角
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

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

num = "IV" # 罗马数字
num.isdigit()   # True
num.isdecimal() # False
num.isnumeric() # True

num = "四" # 汉字
num.isdigit()   # False
num.isdecimal() # False
num.isnumeric() # True

print('this'.isalpha())
>>>True
print('this is ...hero'.isalpha())
>>>False

print('this2018'.isalnum())
>>>True
print('this 2018'.isalnum())
>>>False


'''
islower()、isupper()和istitle()
判断是否为小写、大写和首字母大写
'''

print('abc123'.islower())
>>>True

print('ABC123'.isupper())
>>>True

print('Abc_123'.istitle())
>>>True


'''
isspace()、isprintable()和isidentifier()
分别判断是否为空格、制表符、换行等字符(' '、'\t'、'\n')
判断是否为可打印字符
判断满足标识符定义规则(字符数字和下划线组成,不能数字和开头)
'''

print('\t'.isspace())
>>>True

print('abc'.isprintable())
>>>True

print('2abc'.isidentifier())
>>>False


'''
center()
字符串居中,以指定字符填充指定长度,不指定长度默认使用空格填充
'''

print('Demo'.center(10))
>>>   Demo   

print('Demo'.center(10,'*'))
>>>***Demo***


'''
ljust()和rjust()
类似于center()的用法
ljust()在字符串右侧填充
rjust()在字符串左侧填充
'''

print('Demo'.ljust(10,'*'))
>>>Demo******

print('Demo'.rjust(10,'*'))
>>>******Demo


'''
zfill()
用0填充字符串指定长度,并添加到左侧,如果有+或—符号,会添加到+或-的右侧
'''

print('Demo'.zfill(5))
>>>0Demo

print('+Demo'.zfill(6))
>>>+0Demo


'''
count(sub[start,end])
统计字符串sub出现的次数,可做切片查找统计
'''

print('xyabxyxy'.count('xy',1,7))
>>>1


'''
endswith(sub[start,end])和startswith(sub[start,end)
判断字符串开头和结尾,可做切片,同时也可以传入元祖,只要一个满足返回True
'''

print('abcxyz'.endswith('xyz',4))
>>>False

print('abcxyz'.endswith(('xyz','y','z'),4))
>>>Trueprint('abcxyz'.startswith('cx',2,4))>>>True


'''
find()、rfind()和index()、rindex()
find()寻找字符串中指定字符串的索引位置,如没有返回-1,可切片
index()和find()方法一样,不过当寻找不到时候会报错
rfind()和rindex()也是寻找字符串,不过是从右侧开始查找,其他一样
'''

print('abcxyzXY'.find('xY',4))
>>>-1

print('abcxyzXY'.index('XY',4))
>>>6


'''
replace()
字符串替换,可追加替换个数
'''

print('abcxyzoxy'.replace('xy','XY',1))
>>>abcXYzoxy


'''
expandtabs()
替换字符串中\t默认替换为8个空格,如果\t后边有字符,也会算入8个空格字符里边
'''

print('xyz\tab'.expandtabs())
>>>xyz     ab


'''
translate()和maketrans()
做映射关系使用,可以理解为密码本
'''

int_str = 'abcxyz'
out_str = '123456'

map_table = str.maketrans(int_str, out_str)

my_love = 'I love xyz'
result = my_love.translate(map_table)
print(result)
>>> I love 456


'''
partition()和rpartition()
以指定字符进行分割,并返回三个元素的元祖,如果找不到则返回为空
'''

print('abcxyzopq'.partition('xy'))
>>>('abc', 'xy', 'zopq')

print('abcxyzxyopq'.rpartition('xyc'))
>>>('', '', 'abcxyzxyopq')


'''
split()、rsplit()和splitlines()
split()进行指定字符分割,可以指定分割次数,如果不指定分割字符则以空格为分割符
splitlines()专门用来分割换行符
'''

print('1,2,3'.split(','))
>>>[1,2,3]

print('1 2 3'.split(maxsplit=1))
>>>[1,'2 3']

print('One line\n'.split('\n'))
>>>['One line', '']

print('Two lines\n'.splitlines())
>>>['Two lines']


'''
join()
join很好很强大,join的限制为必须为可迭代对象,字符串、元祖、集合、列表和字典用起来都没问题,前提不能为数字
'''

print('_'.join('Demo'))
>>>D_e_m_o

L3={'name':"malongshuai",'gender':'male','from':'China','age':18}
print('_'.join(L3))
>>>name_gender_from_age


'''
strip()、lstrip()和rstrip()
分别是移除左右两边、左边、右边的字符char。如果不指定chars或者指定为None,则默认移除空白(空格、制表符、换行符)
'''

print(' spacious '.lstrip())
>>>'spacious '

print('spacious '.lstrip('s'))
>>>'pacious '

print('www.example.com'.strip('cmowz.'))
>>>example


'''
casefold()
跟lower()方法一样,不过lower只针对ASCII编码,casefold()对于非中英文的其他语言小写有效,实例只能从网上找到一个
'''

s = 'ß'    # 德语
print(s.casefold())
>>>ss


'''
现在还剩下encode、format和format_map这三个了
其中encode是编码用的
format和format_map是格式化用的
'''
 

  




猜你喜欢

转载自www.cnblogs.com/CrazyDemo/p/9418219.html