python之路 - 字符串

时间:2022-12-12 16:53:30
#!/usr/bin/python3
# def capitalize(self):
# """ 首字母变大写 """
# '''value = 'onion'
# name = value.capitalize()
# print(name)
# '''

# def center(self, width, fillchar=None):
# """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
# value = 'onion'
# name = value.center(20,'—')
# print(name)

# def count(self, sub, start=None, end=None):
# """sub -- 搜索的子字符串"""
# """start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。"""
# """end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置"""
# str = 'blog.csdn.net/imonion'
# put = str.count('n',0,)
# print(put)
# sub = 'net'
# print(str.count(sub))

##def endswith(self, suffix, start=None, end=None):
# """ 是否以 xxx 结束 """
# '''suffix -- 该参数可以是一个字符串或者是一个元素。
# start -- 字符串中的开始位置。
# end -- 字符中结束位置'''
# test = 'this is string example...hei!!!'
# string = test.endswith('hei!!!')
# istring = test.endswith('hei!!')
# print(string,istring)

#def expandtabs(self, tabsize=None):
# """将tab转换成空格,默认一个tab转换成8个空格"""
# """将tab转换成空格,默认一个tab转换成8个空格"""
# test = "username\temail\tpassword\nroot\troot@ROOT.com\t123\nroot\troot@ROOT.com\t123\nroot\troot@ROOT.com\t123"
# root = test.expandtabs(15)
# print(root)

##def find(self, sub, start=None, end=None):
# """ 寻找子序列位置,如果没找到,返回 -1 """
# """如果包含子字符串返回开始的索引值,否则返回-1。"""
# test = 'thisis string !!!'
# istring = test.find('t')
# mstring = test.find('t',1)
# ostring = test.find('t',20)
# print(istring, mstring, ostring)

##def format(*args, **kwargs): # known special case of str.format
# """ 字符串格式化,动态参数,将函数式编程时细说 """
# print("My name is{}, I am {} years old".format('onion','23')) # 不设置指定位置,按默认顺序
# print("My name is{0}, I am {1} years old".format('onion','23')) # 设置指定位置
# print("My name is{1},{0}, I am {1} years old".format('onion','23')) # 设置指定位置

##def index(self, sub, start=None, end=None):
# """ 子序列位置,如果没找到,报错 """
# test = 'runoob example...wow!!'
# put = test.index('exam')
# put2 = test.index('exam',5)
# put3 = test.index('exam',8)
# print(put,put2,put3)

#def isalnum(self):
#""" 是否是字母和数字 """
# test = 'onion123' # 字符串没有空格
# test2 = 'www.onion.com'
# print(test.isalnum(),test2.isalnum())

#def isalpha(self):
#""" 是否是字母 """
# test = 'onion'
# test2 = 'onion...!!!'
# print(test.isalpha(),test2.isalpha())

# def isdigit(self):
# """ 是否是数字 """
# test = '123'
# test2 = 'onion123'
# print(test.isdigit(),test2.isdigit())


## def islower(self):
# """ 是否小写 """
# test = 'onion'
# test2 = 'Onion'
# print(test.islower(),test2.islower())

## def isspace(self):
# """ 检测字符串是否只由空白字符组成。 """
# test = ' '
# test2 = 'onion !'
# print(test.isspace(),test2.isspace())

#def istitle(self):
"""字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。"""
# test = 'This Is String Example...Wow!!!'
# test2 = 'this is string example...Wow!!!'
# print(test.istitle(),test2.istitle())

#def isupper(self):
"""符串中所有的字母是否都为大写。"""
# test = "onion"
# test2 = "ONION"
# print(test.isupper(),test2.isupper())

#def casefold(self):
#test = 'python is Awesome'
#打印小写字符串
#使用casefold的小写字母()
# print('lowercase string:',test.casefold())
#
# firstString = "der Fluß"
# secondString = "der Fluss"
# # 使用casefold进行比较()
# # ß is equivalent to ss
# if firstString.casefold() == secondString.casefold():
# print('The strings are equal.')
# else:
# print('The strings are not equal.')
#def format_map(self, mapping):
"""format_map()方法类似于str.format(**映射),
不同之处在于str.format(**映射)创建一个新的字典,
而str.format_map(映射)不创建。"""
# point = {'x':4,'y':-5}
# print('{x} {y}'.format_map(point))
#
# point = {'x':4,'y':-5, 'z': 0}
# print('{x} {y} {z}'.format_map(point))
# #format_map()如何与dict子类一起使用?
# class Coordinate(dict):
# def __missing__(self, key):
# return key
#
#
# print('({x}, {y})'.format_map(Coordinate(x='6')))
# print('({x}, {y})'.format_map(Coordinate(y='5')))
# print('({x}, {y})'.format_map(Coordinate(x='6', y='5')))

#def isdecimal(self):
# """字符串是否只包含十进制字符。这种方法只存在于unicode对象"""
# test = "Onion2018"
# print (test.isdecimal())
#
# test1 = "23443434"
# print (test1.isdecimal())

#def isprintable(self):
# """如果字符串是Python中的有效标识符,则isidentifier()方法返回True。如果不是,则返回False。"""
# str = 'Python'
# print(str.isidentifier())
# str = 'Py thon'
# print(str.isidentifier())
# str = '22Python'
# print(str.isidentifier())
# str = ''
# print(str.isidentifier())
#
# """isidentifier()的更多例子"""
# str = 'root33'
# if str.isidentifier() == True:
# print(str, 'is a valid identifier.')
# else:
# print(str, 'is not a valid identifier.')
#
# str = '33root'
# if str.isidentifier() == True:
# print(str, 'is a valid identifier.')
# else:
# print(str, 'is not a valid identifier.')
#
# str = 'root 33'
# if str.isidentifier() == True:
# print(str, 'is a valid identifier.')
# else:
# print(str, 'is not a valid identifier.')
#def join(self, iterable):
"""用于将序列中的元素以指定的字符连接生成一个新的字符串。"""
#1.join()方法如何工作?
# numList = ['1', '2', '3', '4']
# seperator = ', '
# print(seperator.join(numList))
#
# numTuple = ('1', '2', '3', '4')
# print(seperator.join(numTuple))
#
# s1 = 'abc'
# s2 = '123'
#
# """s2的每个字符连接到s1的前面"""
# print('s1.join(s2):', s1.join(s2))
#
# """s1的每个字符连接到s2的前面"""
# print('s2.join(s1):', s2.join(s1))
#2.join()方法如何用于集合?
# test = {'2', '1', '3'}
# s = ', '
# print(s.join(test))
#
# test = {'Python', 'Java', 'Ruby'}
# s = '->->'
# print(s.join(test))

#def ljust(self, width, fillchar=None):
"""返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。"""
"""width -- 指定字符串长度。"""
"""fillchar -- 填充字符,默认为空格。"""
# str = "Runoob example....wow!!!"
# print (str.ljust(50, '*'))

#def lower(self):
# """转换字符串中所有大写字符为小写"""
# str = "Runoob EXAMPLE....WOW!!!"
# print( str.lower() )

#def lstrip(self, chars=None):
"""lstrip() 方法用于截掉字符串左边的空格或指定字符。"""
"""chars --指定截取的字符。"""
# str = " this is string example....wow!!! ";
# print( str.lstrip() );
# str = "88888888this is string example....wow!!!8888888";
# print( str.lstrip('8') );

#smaketran(self, *args, **kwargs):
# pass

#def partition(self, sep):
"""用来根据指定的分隔符将字符串进行分割"""
# str = "http://www.w3cschool.cc/"
# print(str.partition("://"))

#def replace(self, old, new, count=None):
# """把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次"""
# """old -- 将被替换的子字符串。"""
# """new -- 新字符串,用于替换old子字符串。"""
# """max -- 可选字符串, 替换不超过 max 次"""
# str = "www.w3cschool.cc"
# print ("菜鸟教程旧地址:", str)
# print ("菜鸟教程新地址:", str.replace("w3cschool.cc", "runoob.com"))
# str = "this is string example....wow!!!"
# print (str.replace("is", "was", 3))

#def rfind(self, sub, start=None, end=None):
# """返回字符串最后一次出现的位置,如果没有匹配项则返回-1"""
# """str -- 查找的字符串"""
# """beg -- 开始查找的位置,默认为0"""
# """end -- 结束查找位置,默认为字符串的长度。"""
# str1 = "this is really a string example....wow!!!"
# str2 = "is"
#
# print (str1.rfind(str2))
#
# print (str1.rfind(str2, 0, 10))
# print (str1.rfind(str2, 10, 0))
#
# print (str1.find(str2))
# print (str1.find(str2, 0, 10))
# print (str1.find(str2, 10, 0))


#def rindex(self, sub, start=None, end=None):
# """返回子字符串 str 在字符串中最后出现的位置,
# 如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。"""
# str1 = "this is really a string example....wow!!!"
# str2 = "is"
#
# print (str1.rindex(str2))
# print (str1.rindex(str2,10))

#def rjust(self, width, fillchar=None):
# """返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
# 如果指定的长度小于字符串的长度则返回原字符串"""
# str = "this is string example....wow!!!"
# print (str.rjust(50, '*'))

#def rpartition(self, sep):
# string = "Python is fun"
#
# # 'is' separator is found
# print(string.rpartition('is '))
#
# # 'not' separator is not found
# print(string.rpartition('not '))
#
# string = "Python is fun, isn't it"
#
# # splits at last occurence of 'is'
# print(string.rpartition('is'))

#def rsplit(self, sep=None, maxsplit=-1):
"""rsplit()方法从指定分隔符的右侧分割字符串并返回字符串列表。"""
#text= 'Love thy neighbor'

# splits at space
# print(text.rsplit())
#
# grocery = 'Milk, Chicken, Bread'
#
# # splits at ','
# print(grocery.rsplit(', '))
#
# # Splitting at ':'
# print(grocery.rsplit(':'))

#def rstrip(self, chars=None):
# """删除 string 字符串末尾的指定字符(默认为空格)."""
# str = " this is string example....wow!!! "
# print (str.rstrip())
# str = "*****this is string example....wow!!!*****"
# print (str.rstrip('*'))

#def split(self, sep=None, maxsplit=-1):
# """split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串"""
# str = "this is string example....wow!!!"
# print (str.split( ))
# print (str.split('i',1))
# print (str.split('w'))


#def splitlines(self, keepends=None):
# """splitlines() 按照行('\r', '\r\n', \n')分隔
# 返回一个包含各行作为元素的列表,如果参数 keepends 为 False,
# 不包含换行符,如果为 True,则保留换行符。"""
# grocery = 'Milk\nChicken\r\nBread\rButter'
#
# print(grocery.splitlines())
# print(grocery.splitlines(True))
#
# grocery = 'Milk Chicken Bread Butter'
# print(grocery.splitlines())

#def startswith(self, prefix, start=None, end=None):
# """用于检查字符串是否是以指定子字符串开头,
# 如果是则返回 True,否则返回 False。
# 如果参数 beg 和 end 指定值,则在指定范围内检查。"""
# str = "this is string example....wow!!!"
# print (str.startswith( 'this' ))
# print (str.startswith( 'string', 8 ))
# print (str.startswith( 'this', 2, 4 ))

#def strip(self, chars=None):
#"""用于移除字符串头尾指定的字符(默认为空格)"""
# str = "*****this is string example....wow!!!*****"
# print (str.strip( '*' ))

#def swapcase(self):
# str = "this is string example....wow!!!"
# print (str.swapcase())
#
# str = "This Is String Example....WOW!!!"
# print (str.swapcase())

#def title(self):
# """返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())。"""
# str = "this is string example from runoob....wow!!!"
# print (str.title())

#def translate(self, table):
"""方法根据参数table给出的表(包含 256 个字符)转换字符串的字符,要过滤掉的字符放到 deletechars 参数中"""
# intab = "aeiou"
# outtab = "12345"
# trantab = str.maketrans(intab, outtab) # 制作翻译表
#
# str = "this is string example....wow!!!"
# print(str.translate(trantab))
#
# # 制作翻译表
#bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
#
# # 转换为大写,并删除字母o
# print(b'runoob'.translate(bytes_tabtrans, b'o'))

#def upper(self):
# """将字符串中的小写字母转为大写字母。"""
#
# str = "this is string example from runoob....wow!!!";
# print ("str.upper() : ", str.upper())

#def zfill(self, width):
# """返回指定长度的字符串,原字符串右对齐,前面填充0。"""
# str = "this is string example from runoob....wow!!!"
# print ("str.zfill : ",str.zfill(40))
# print ("str.zfill : ",str.zfill(50))