# 字符串
# 字符串更新
strvar = "hello world"
print("已更新字符串:", strvar[:6] + 'runoob') # 已更新字符串: hello runoob
# 转义字符
# \a 响铃
print('\a')
# \b 退格
print("Hello \bworld")
# \000 空
print("Hello\000world") # Helloworld
# \r 回车,将\r后面的内容移到字符串开头,并逐一替换开头部分的字符,直到将\r后面的内容完全替换完成
print("Hello \rworld") #
# \r 实现百分比进度
import time
# for i in range(101):
# print("\r{}%".format(i), end='')
# time.sleep(0.05)
# 原型化输出字符串:r"hello \n world" 或 R"hello \n world"
print(r"Hello \n World") # Hello \n World
print(R"Hello \n World") # Hello \n World
# 字符串格式化
print("我叫%s今年的%d岁" % ("小明", 10)) # 我叫小明今年的10岁
print('我叫{}今年{}岁'.format("小明", 10)) # 我叫小明今年10岁
# 字符串内建函数
# capitalize():/ˈkæpɪtəlaɪz/将字符串的第一个字符转换为大写
strvar = 'abcdefg'
print(strvar.capitalize()) # Abcdefg
# center(width,fillchar): 返回一个指定的宽度width居中的字符串fillchar为填充的字符,默认为空格
# 注意:如果witch小于字符串宽度直接返回字符串,否则使用fillchar填充
strvar = 'helloworld'
print(strvar.center(20, '*')) # *****helloworld*****
print(strvar.center(5, "*")) # helloworld
# ljust(width,[fillchar]):返回一个原字符串左对齐,并使用fillchar填充至长度width的新字符串,fillchar默认为空格
strvar = 'hello world'
print(strvar.ljust(30, '*')) # hello world*******************
print(strvar.ljust(10, "*")) # hello world
# rjust(width,[fillchar]):返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度width的新字符串
strvar = 'hello world'
print(strvar.rjust(30,'*')) # *******************hello world
print(strvar.rjust(10,'*')) # hello world
# count(str,beg=0,end=len(string)):返回str在string里面出现的次数,如果beg或者end指定,则返回指定范围内str出现次数
strvar = "qazwsxedcqazwsxedcqazwsxedc"
print(strvar.count("w", 2, 20)) # 2
# encode(encoding,error='strict'):以encoding指定的编码格式编码字符串
# 使用UTF-8编码
strvar_utf8 = "使用UTF8编码"
print(strvar_utf8.encode("utf-8")) # b'\xe4\xbd\xbf\xe7\x94\xa8UTF8\xe7\xbc\x96\xe7\xa0\x81'
print(strvar_utf8.encode("UTF-8")) # b'\xe4\xbd\xbf\xe7\x94\xa8UTF8\xe7\xbc\x96\xe7\xa0\x81'
# 使用GBK编码
strvar_gbk = "使用GBK编码"
print(strvar_gbk.encode('gbk')) # b'\xca\xb9\xd3\xc3GBK\xb1\xe0\xc2\xeb'
print(strvar_gbk.encode('GBK')) # b'\xca\xb9\xd3\xc3GBK\xb1\xe0\xc2\xeb'
# decode(): 解码
# 解utf8
print(strvar_utf8.encode('utf-8').decode("utf-8")) # 使用UTF8编码
# 解gbk
print(strvar_gbk.encode('gbk').decode('gbk')) # 使用GBK编码
# endswith(suffix,beg=0,end=len(string)):检查字符串是否以suffix结束,如果beg或者end指定则检查指定的范围内是否以suffix结束,如果是,返回True,否则返回False
strvar = 'qazwsxedc'
print(strvar.endswith("c")) # True
print(strvar.endswith("a")) # False
print(strvar.endswith('a', 0, 2)) # True
# startswith(subtar,beg=0,end=len(string)):检查字符串是否以子字符串substr开头,是则返回True,否则返回False,如果beg和end指定值,则在指定范围内检查
strvar = 'qazwsx'
print(strvar.startswith('qaz')) # True
print('========================================')
# find(str,beg=0,end=len(string)): 检测str是否包含在字符串中,如果指定范围beg和end,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
# rfind(str,beg=0,end=len(string)):类似与find函数,不过是从右边开始查找
strvar = 'qazwsxedc'
print(strvar.find('c')) # 8
print(strvar.find('s', 2, 5)) # 4
print(strvar.find('t')) # -1
# index(str,beg=0,end=len(string)):和find方法一样,只不过如果str不在字符串中会报一个异常
# rindex(str,beg=0,end=len(string)):类似于index(),不过是从右边开始查找。
# strvar = 'qazwsx'
# print(strvar.index('1')) # ValueError: substring not found
# isalnum():如果字符串至少有一个字符,并且所有字符都是字母或中文,则返回True,否则返回False
strvar = 'qazwsx'
print(strvar.isalnum()) # True
strvar = '1234'
print(strvar.isalnum()) # True
strvar = '123qaz'
print(strvar.isalnum()) # True
strvar = '123_qaz'
print(strvar.isalnum()) # False
# isdecimal():检查字符串中是否只包含十进制字符,如果是返回True,否则返回False
strvar = '12345'
print(strvar.isdecimal()) # True
# isalpha():如果字符串中至少又一个字符,并且所有字符都是字母或中文则返回True否则返回False
strvar = 'qaz'
print(strvar.isalpha()) # True
strvar = '汉字'
print(strvar.isalpha()) # True
strvar = 'qaz_汉字'
print(strvar.isalpha()) # False
strvar = 'qaz汉字'
print(strvar.isalpha()) # True
# isdigit():如果字符串只包含数字则返回True,否则返回False
strvar = '123456'
print(strvar.isdigit()) # True
strvar = 'qazwsx'
print(strvar.isdigit()) # False
# isnumeric():如果字符串中只包含数字字符串,则返回True,否则返回False.数字可以是:Unicode数字,全角数字(双字节),罗马数字,汉字数字
strvar = '1/2'
print(strvar.isnumeric()) # False
strvar = '123'
print(strvar.isnumeric()) # True
strvar = '一二三'
print(strvar.isnumeric()) # True
# islower():如果字符串中至少包含一个区分大小写的字符,切所有字符都是小写,返回True,否则返回False
strvar = 'qaz'
print(strvar.islower()) # True
strvar = 'QAZ'
print(strvar.islower()) # False
# isupper():如果字符串中包含至少一个区分大小写的字符,并且所有字符都是大写,则返回True,否则返回False
strvar = 'qaz'
print(strvar.isupper()) # False
strvar = 'QAZ'
print(strvar.isupper()) # True
# isspace():如果字符串中只包含空白,则返回True,否则返回False
strvar = ' '
print(strvar.isspace()) # True
strvar = 'hello world'
print('空白:', strvar.isspace()) # False
# istitle():字符串中所有的单词拼写首字母是否为大写,是返回True,否返回False
strvar = 'Hello Every One!!!'
print(strvar.istitle()) # True
strvar = 'Hello every one!!!'
print(strvar.istitle()) # False
# join(seq):以指定字符串作为分割符,将seq(序列)中的所有元素合并为一个新的字符串
seq = ('1', '2', '3', '4')
seq_new = ''.join(seq)
print(seq_new) # 1234
seq = ['1', '2', '5', '7']
seq_new = ' '.join(seq)
print(seq_new) # 1 2 5 7
seq = {'1', '2', '4', '5'}
seq_new = '*'.join(seq)
print(seq_new) # 5*1*4*2
# len(string):返回字符串长度
strvar = '123456'
print(len(strvar)) # 6
# lower():转换字符串中所有大写字符为小写
strvar = 'hello WORLD'
print(strvar.lower()) # hello world
# strip():移除字符串两端的空格或指定字符串
strvar = ' hello world '
print(strvar.strip()) # hello world
strvar = '888hello world88888'
print(strvar.strip('8')) # hello world
print('1========================')
# lstrip():截掉左边的空格或指定字符串
strvar = ' hello world'
print(strvar.lstrip()) # hello world
strvar = '***hello world'
print(strvar.lstrip('*')) # hello world
# rstrip():截掉右边的空格或指定字符
strvar = 'hello world '
print(strvar.rstrip()) # hello world
strvar = 'hello world***'
print(strvar.rstrip('*')) # hello world
# maketrans(x, [y], [z]):创建字符映射的转换表,x:必需,字符串中要替代的字符组成的字符串。y:可选,相应的映射字符的字符串。z:可选,要删除的字符。x,y两个字符串的长度必需相同
# translate(table,[deletechars]):根据参数table给出的表,转换字符串的字符,要滤掉的字符放到deletechars参数中。table:翻译表,翻译表是通过maketrans()方法转换而来。deletechars:字符串中要过滤的字符列表
"""
注:
str.translate(table)
bytes.translate(table, [deletechars])
bytearray.translate(table, [deletechars])
"""
# 将字母R替换为N
strvar = 'Runoob'
strvar_mt = strvar.maketrans('R', 'N')
print(strvar_mt) # {82: 78}
print(strvar.translate(strvar_mt)) # Nunoob
# 使用字符串设置要替换的字符,一一对应
intab = 'aeiou'
outtab = '12345'
strvar = 'this is string example ... wow'
strvar_mt = strvar.maketrans(intab, outtab)
print(strvar.translate(strvar_mt)) # th3s 3s str3ng 2x1mpl2 ... w4w
# 设置要删除的字符参数
strvar = 'google runoob taobao'
intab = 'gra'
outtab = 'eto'
delete = 'o'
strvar_mt = strvar.maketrans(intab, outtab, delete)
print(strvar.translate(strvar_mt)) # eele tunb tobo
# max(str):返回字符串中最大的字母
strvar = 'abcde'
print(max(strvar)) # e
# min(str):返回字符串中最小的字母
strvar = "abcde"
print(min(strvar)) # a
# replace(old,new,[max]):将字符串中的old替换成new。如果max指定,则替换不超过max次
strvar = 'google runoob taobao'
print(strvar.replace('o', '8', 2)) # g88gle runoob taobao
# split(str='',num=string.count(str)):以str为分割符截取字符串,如果num有指定值,则仅截取num+1个字符串,返回分割后的字符串列表
strvar = 'google runoob taobao'
print(strvar.split(' ')) # ['google', 'runoob', 'taobao']
print(strvar.split(' ', 1)) # ['google', 'runoob taobao']
# swapcase():将字符串中大写转换为小写,小写转换为大写
strvar = 'Hello World'
print(strvar.swapcase()) # hELLO wORLD
# title():标题化字符串,单词首字母都是大写
strvar = 'helloworld'
print(strvar.title()) # Helloworld
strvar = 'hello world'
print(strvar.title()) # Hello World
# upper():转换字符串中小写字母为大写
strvar = 'hello world'
print(strvar.upper()) # HELLO WORLD
# zfill(width):返回指定长度的字符串,原字符串右对齐,前面填充0
strvar = 'helloworld'
print(strvar.zfill(20)) # 0000000000helloworld