Python数据类型

本文详细介绍了Python中字符串的各种方法,包括大小写转换、查找、替换、格式化等功能,提供了丰富的示例帮助理解。

 包含Python的str dict list tup set


 Python —— Str

# capitalize()

# Python capitalize()将字符串的第一个字母变成大写,其他字母变小写。对于 8 位字节编码需要根据本地环境。
#  该方法返回一个首字母大写其他字母小写的字符串
# str.capitalize()  无参
# s = 'gx626A&^9x#8+=D&zl9n^m+_)yDDD^r(y(y=2^uk_jcr#o9itmlok'
# s = ' a,b'
# print(s.capitalize())
# 注意,该字符串首字母前面不可以有空格 s.strip().capitalize()


# center()

# Python center() 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。
#  该方法返回一个原字符串居中,并使左右填充制定长度的新字符串,默认填充为空格
# str.center(width[, fillchar])
# width -- 字符串的总宽度
# fillchar -- 填充字符

# s = 'gx626A&^9x#8+=D&zl9n^m+_)yDDD^r(y(y=2^uk_jcr#o9itmlok'
# print(s.center(70, '*'))  # **********gx626A&^9x#8+=D&zl9n^m+_)y^r(y(y=2^uk_jcr#o9itmlok**********
# 注意:
#   不提供 char 参数则默认为空格
#   当 width 参数小于等于原字符串的长度时,原样返回
#   无法使左右字符数相等时候,左侧字符会比右侧少 1


# count()

# Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
#  str.count(sub, start= 0,end=len(string))
# sub -- 搜索的子字符串
# start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
# end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置
# 该方法返回子字符串在字符串中出现的次数
# s = 'gx626A&^9x#8+=D&zl9n^m+_)yDDD^r(y(y=2^uk_jcr#o9itmlok'
# print(s.count('D', 0,28))

# 第一个位置为统计的字符,第二个为开始的索引位置,第三个位置为结束位置,后两个参数可跟可不跟


# decode()

# Python decode() 方法以 encoding 指定的编码格式解码字符串。默认编码为字符串编码
# str.decode(encoding='UTF-8',errors='strict')
# encoding -- 要使用的编码,如"UTF-8"。
# errors -- 设置不同错误的处理方案。默认为 'strict',
# 意为编码错误引起一个UnicodeError。
# 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace'
# 以及通过 codecs.register_error() 注册的任何值
# 该方法返回解码后的字符串

# s = s.encode('gbk', 'strict')
# print('Encoded string:', s)
# print('Decoded string:', s.decode('gbk', 'strict'))


# encode()

# Python encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。
# str.encode(encoding='UTF-8',errors='strict')
# encoding -- 要使用的编码,如"UTF-8"。
# errors -- 设置不同错误的处理方案。默认为 'strict',
# 意为编码错误引起一个UnicodeError。
# 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace'
# 以及通过 codecs.register_error() 注册的任何值
# 该方法返回解码后的字符串


# 该方法返回编码后的字符串

# print(s.encode('utf8', errors='strict'))
# 注意:errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError
# 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值


# endswith()
# 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。


# 如果字符串含有指定的后缀返回True,否则返回False
# s = 'this is string example....wow!!!'
# a = 'wow!!!'
# print(s.endswith(a))
# print(s.endswith(a, 20))
# a = 'is'
# print(s.endswith(a, 2, 4))  # 判断的是is
# print(s.endswith(a, 2, 6))
# 注意:不只是判断某个字符在最后面,也可以配合后两个参数,进行判断某个字符在中间的某个位置


# startswith()

# Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。
# 如果参数 beg 和 end 指定值,则在指定范围内检查。
# str.startswith(str, beg=0, end=len(string))
# s = 'this is string example'
# print(s.startswith('this'))   # true
# print(s.startswith('this', 2,4))  # false
# print(s.startswith('is', 2,4))  # true


# expandtabs()

# Python expandtabs() 方法把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。
# str.expandtabs(tabsize=8)   tabsize -- 指定转换字符串中的 tab 符号('\t')转为空格的字符数。

# 该方法返回字符串中的 tab 符号('\t')转为空格后生成的新字符串

# s = 'this is\tstring example....wow!!!'
# print(s)  # this is    string example....wow!!!
# print(s.expandtabs())  # this is string example....wow!!!
# print(s.expandtabs(5))  # this is   string example....wow!!!
# 注意:pyhton3直接打印字符串,\t并没有生效,不加参数也没效果,只有制定参数后,才能生效


# find()

# 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1
# 如果包含子字符串返回开始的索引值,否则返回-1。
# str.find(str, beg=0, end=len(string))
# str -- 指定检索的字符串
# beg -- 开始索引,默认为0。
# nd -- 结束索引,默认为字符串的长度。
# 如果包含子字符串返回开始的索引值,否则返回-1

# str1 = "this is string example....wow!!!"
# str2 = "exam"
# print(str1.find(str2))
# print(str1.find(str2, 10,))   # 在指定范围内
# print(str1.find(str2, 15, 19))  # 在指定范围内
# print(str1.find(str2, 29))  # 不在起始范围
# 注意:只有在指定范围内,才返回索引位置,否则返回 -1

# rfind()

# Python rfind() 返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。
# str.rfind(str, beg=0 end=len(string))
# s = 'this is really a string example'
# substr = 'is'
# print(s.rfind(substr))  # 5
# print(s.rfind(substr, 0, 10))  # 5
# print(s.rfind(substr, 10, 0))  # -1


# format()
# Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
# 基本语法是通过 {} 和 : 来代替以前的 % 。
# format 函数可以接受不限个参数,位置可以不按顺序。
# 摘自:http://www.runoob.com/python/att-string-format.html

# dic = '{} {}'.format('hello', 'world')  # 不设置指定位置,按默认顺序
# dic = '{0} {1}'.format('hello', 'world')  # 设置指定位置
# dic = '{1} {0} {1}'.format('hello', 'world')  # 设置指定位置
# dic = ('姓名:{name},年龄:{age}'.format(name='egon', age=11 ))  # 设置参数
# dic = {'name': 'egon', 'age':21}  # 通过字典设置参数
# li = ['egon', 21]  # 通过列表索引设置参数
# print('姓名:{0[0]} | 年龄:{0[1]}'.format(li))  # '0'是必须的

# 还可以传入对象
# class Bar(object):
#     def __init__(self, value):
#         self.value = value
# bar = Bar(2)
# print('Value值为:{0.value}'.format(bar))

# 数字格式化
# print('{:.2f}'.format(3.1415926))  # 3.14
# 我认为最骚的用法
# print(format('最骚操作','^40',))


# index()

# Python index() 方法检测字符串中是否包含子字符串 str ,
# 如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,
# 该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
# 如果包含子字符串返回开始的索引值,否则抛出异常。
# str.index(str, beg=0, end=len(string))

# str1 = "this is string example....wow!!!"
# str2 = "exam"
#
# print(str1.index(str2))      # 15
# print(str1.index("t"))      # 0
# print(str1.index(str2, 10))  # ValueError: substring not found
# print(str1.index(str2, 40))  # 15


# rindex()

# Python rindex() 返回子字符串 str 在字符串中最后出现的位置,
# 如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。
# str.rindex(str, beg=0 end=len(string))
# 返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常
# s = 'this is string example'
# s1 = 'is'
# print(s.index(s1))  # 2
# print(s.rindex(s1))  # 5



# isalnum()

# 方法检测字符串是否由字母和数字组成
# 返回值:如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
# str.isalnum()  # 无参数

# s = 'this is2008'
# s1 = '2008'
# s2 = 'this'
# print(s.isalnum())  # false
# print(s1.isalnum())  # true
# print(s2.isalnum())  # true
# 注意:字符串中不能有空格

# isalpha()

# Python isalpha() 方法检测字符串是否只由字母组成。
# 返回值:如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False
# str.isalpha() # 无参数


# s = 'this'
# s1 = 'this is'
# s2 = 'this8'
# s3 = 'this!'
# print(s.isalpha()  # true
# print(s1.isalnum())  # false
# print(s2.isalpha())  # false
# print(s3.isalpha())  # false
# 注意:这个方法只有纯字母才会返回true,加个标点符号都不行


# isdecimal()

# Python isdecimal() 方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
# 注意:定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可
# 如果字符串是否只包含十进制字符返回True,否则返回False。
# str.isdecimal() # 无参

# s = u'this2009'
# s1 = u'2382'
# s2 = u'this'
# print(s.isdecimal())  # false
# print(s1.isdecimal())  # true
# print(s2.isdecimal())  # false


# isdigit()

# Python isdigit() 方法检测字符串是否只由数字组成。
# str.isdigit()  # 无参数

# s = '12347'
# s1 = 'this'
# print(s.isdigit())  # true
# print(s1.isdigit())  # false


# islower()
# Python islower() 方法检测字符串是否由小写字母组成。
# 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
# str.islower()  无参数

# s = 'THis IS String...!'
# s1 = 'this is string'
# print(s.islower())  # false
# print(s1.islower())  # true


# isnumeric()

# Python isnumeric() 方法检测字符串是否只由数字组成。这种方法是只针对unicode对象。
# 注:定义一个字符串为Unicode,只需要在字符串前添加 'u' 前缀即可
# 如果字符串中只包含数字字符,则返回 True,否则返回 False
# str.isnumeric()  无参数

# s = u'this2008'
# s1 = u'234323'

# print(s.isnumeric())  # false
# print(s1.isnumeric())  # true


# isspace()

# Python isspace() 方法检测字符串是否只由空格组成。
# 如果字符串中只包含空格,则返回 True,否则返回 False.
# str.isspace() 无参数

# s = '          '
# s1 = 'this is string'
# print(s.isspace())  # true
# print(s1.isspace())  # false


# title()

# Python title() 方法返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())。
# str.title()  无参
# 返回"标题化"的字符串,就是说所有单词都是以大写开始。
# s = 'This Is String'
# s1 = 'this is string'
# print(s.title())  # This Is String
# print(s1.title())  # This Is String

# istitle()

# Python istitle() 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
# 如果字符串中所有的单词拼写首字母是否为大写,且其他字母为小写则返回 True,否则返回 False.
# str.istitle() 无参数

# s = 'This Is String'
# s1 = 'This is string'
# print(s.istitle())  # true
# print(s1.istitle())  # false

# upper()

# Python upper() 方法将字符串中的小写字母转为大写字母。
# str.upper()  无参
# 返回小写字母转为大写字母的字符串。

# s = 'this is string example!'
# print(s.upper())  # THIS IS STRING EXAMPLE!


# isupper()

# Python isupper() 方法检测字符串中所有的字母是否都为大写。
# 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
# str.isupper() 无参数

# s = 'THIS IS STRING'
# s1 = 'This is string'
# print(s.isupper())  # true
# print(s1.isupper())  # false


# join()

# Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
# str.join(sequence)  sequence:要连接的元素序列
# 返回通过指定字符连接序列中元素后生成的新字符串。

# s = '_'
# seq = ('a', 'b', 'c')
# print(s.join(seq))  # a_b_c


# ljust()

# Python ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
# str.ljust(width[, fillchar])
#  width -- 指定字符串长度,
# fillchar -- 填充字符,默认为空格
# 返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串

# s = 'this is string'
# print(s.ljust(40, '*'))  # this is string**************************


# rjust()
# Python rjust() 返回一个原字符串右对齐,
# 并使用空格填充至长度 width 的新字符串。
# 如果指定的长度小于字符串的长度则返回原字符串。
# str.rjust(width, [, fillchar])
# width -- 指定填充指定字符后中字符串的总长度
# fillchar -- 填充的字符,默认为空格。
# 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。
# 如果指定的长度小于字符串的长度则返回原字符串

# s = 'this is string example'
# print(s.rjust(30, '*'))  # ********this is string example
# 注意:如果指定宽度小于字符串本身,则返回字符串本身


# lower()
# Python lower()
# 方法转换字符串中所有大写字符为小写
# str.lower() 无参数
# 返回值:返回将字符串中所有大写字符转换为小写后生成的字符串。

# s = 'This IS string'
# print(s.lower())  # this is string


# lstrip()
# Python lstrip() 方法用于截掉字符串左边的空格或指定字符。
# str.lstrip([chars])  # chars 指定截取的字符
# 返回截掉字符串左边的空格或指定字符后生成的新字符串

# s = '    this is string      '
# s1 = '3333this is string!333333'
# print(s.lstrip())  # this is string
# print(s1.lstrip('3'))  # this is string!333333


# maketrans()
# Python maketrans() 方法用于创建字符映射的转换表,
# 对于接受两个参数的最简单的调用方式,第一个参数是字符串,
# 表示需要转换的字符,第二个参数也是字符串表示转换的目标。
# 注:两个字符串的长度必须相同,为一一对应的关系。
# str.maketrans(intab, outtab)
# intab -- 字符串中要替代的字符组成的字符串。
# outtab -- 相应的映射字符的字符串。
# 返回字符串转换后生成的新字符串。
# 摘自:http://www.runoob.com/python3/python3-string-maketrans.html

# intab = "aeiou"
# outtab = "12345"
# trantab = str.maketrans(intab, outtab)
# str = "this is string example....wow!!!"
# print(str.translate(trantab))  # th3s 3s str3ng 2x1mpl2....w4w!!!


# max()

# Python max() 方法返回字符串中最大的字母。
# max(str)  # str 字符串
# 返回字符串中最大的字母
# s = 'this is string'
# s1 = 'abcdefghijklmnopqrstuvwxyz'
# print(max(s))
# print(max(s1))


# min()

# Python min() 方法返回字符串中最小的字母。
# min(str)  # str 字符串
# 返回字符串中最小的字母。
# s = 'this is real string example wow!!!'
# s1 = 'abcdefghijklmanopqrstuvwxyz'
# print(min(s))
# print(min(s1))
# 注意:字符串不能有空格


# partition()

# partition() 方法用来根据指定的分隔符将字符串进行分割。
# 如果字符串包含指定的分隔符,则返回一个3元的元组,
# 第一个为分隔符左边的子串,第二个为分隔符本身,
# 第三个为分隔符右边的子串
# str.partition(str)
# 返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

# s = 'http://www.baidu.com'
# s1 = 'abcdefg'
# print(s.partition('://'))   # ('http', '://', 'www.baidu.com')
# print(s1.partition('d'))   # ('abc', 'd', 'efg')
# 注意,对应的,有rpartition()函数,从右侧开始查找

# print(s.rpartition('://'))   # ('http', '://', 'www.baidu.com')
# print(s1.rpartition('d'))   # ('abc', 'd', 'efg')



# replace()

# Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
# str.replace(old,new[,max])
# s = 'this is string example,this is really string'
# print(s.replace('is', 'was'))  # thwas was string example,thwas was really string
# print(s.replace('is', 'was', 3))  # thwas was string example,thwas is really string


# strip()

# 删除str两侧的指定的字符,默认是空格,
# str.strip([char])  char 指定的字符
# s = 'ccccccthis is really exampleccccccccc'
# print(s.strip('c'))  # this is really example
# 注意:还有两个类似的方法,
# str.lstrip('c')  # 去除字符串左侧的指定的字符
# str.rstrip('c')  # 去除字符串右侧的指定的字符
# print(s.lstrip('c'))  # this is really exampleccccccccc
# print(s.rstrip('c'))  # ccccccthis is really example

# split()

# Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
# str.split(str="", num=string.count(str))
# str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
# num -- 分割次数
# 返回分割后的字符串列表。

# s = 'this is string example'
# s1 = 'this /is /string /example'
# print(s.split())  # ['this', 'is', 'string', 'example']
# print(s.split(' '))  # ['this', 'is', 'string', 'example']
# print(s.split(' ', 2))  # ['this', 'is', 'string example']
# print(s1.split('/', 2))  # ['this ', 'is ', 'string /example']
# 注意,不仅可以指定以什么来分割,还可以指定分割次数

# splitlines()

# Python splitlines() 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
# str.splitlines([keepends])  keepends -- 在输出结果里是否去掉换行符('\r', '\r\n', \n'),默认为 False,不包含换行符,如果为 True,则保留换行符。
# 返回一个包含各行作为元素的列表。

# s = 'ab c\n\nde fg\rkl\r\n'
# s2 = 'ab c\n\nde fg\rkl\r\n'
# print(s.splitlines())  # ['ab c', '', 'de fg', 'kl']
# print(s.splitlines(True))  # ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
# 注意,默认不保留换行符,设置为True,则保留换行符,只是做分割而已






# swapcase()

# Python swapcase() 方法用于对字符串的大小写字母进行转换。
# str.swapcase()  无参
# 返回大小写字母转换后生成的新字符串
# s = 'This IS String'
# print(s.swapcase())  # tHIS is sTRING


# Python3 translate()方法

# translate() 方法根据参数table给出的表(包含 256 个字符)转换字符串的字符,要过滤掉的字符放到 deletechars 参数中。
# str.translate(table[, deletechars]);
# bytes.translate(table[, delete])
# bytearray.translate(table[, delete])
# table -- 翻译表,翻译表是通过 maketrans() 方法转换而来。
# deletechars -- 字符串中要过滤的字符列表。
# 返回翻译后的字符串,若给出了 delete 参数,则将原来的bytes中的属于delete的字符删除,剩下的字符要按照table中给出的映射来进行映射 。
# 摘自:http://www.runoob.com/python3/python3-string-translate.html
# 注意:python2和python3有所不同,这里以python3为例

# intab = 'aeiou'
# outtab = '12345'
# trantab = str.maketrans(intab, outtab)  # 制作翻译表
# s = 'this is string example'
# print(s.translate(trantab))  # th3s 3s str3ng 2x1mpl2

# 制作翻译表
# bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')

# 转换为大写,并删除字母o
# print(b'runoob'.translate(bytes_tabtrans, b'o'))  # b'RUNB'


# zfill()

# Python zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
# str.zfill(width)  width -- 指定字符串的长度。原字符串右对齐,前面填充0。
# 返回指定长度的字符串

# s = 'this is string example!'
# print(s.zfill(40))  # 00000000000000000this is string example!
# 这个可以在数据传送中应用,比如,每次传送1024k,不够1024的可以zfill一下,补上
View Code

参考:http://www.runoob.com/python/python-strings.html

 


 

 

End

转载于:https://www.cnblogs.com/Neeo/p/7735341.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值