判断一个数是否是回文数(正反读一样):
x = "12321"
"是回文数" if x == x[::-1] else "不是回文数"
'是回文数'
x = "12345"
"是回文数" if x == x[::-1] else "不是回文数"
'不是回文数'
处理字符串的方法:
大小写字母换来换去:
capitalize()casefold() title()
swapcase() upper() lower()
x = "I love Python"
x.capitalize()
'I love python'
x.casefold()
'i love python'
x.title()
'I Love Python'
x.swapcase()
'i LOVE pYTHON'
x.upper()
'I LOVE PYTHON'
x.lower()
'i love python'
左中右对齐的方法:
center(width,fillchar = ' ') ljust(width,fillchar = ' ')
rjust(width,fillchar = ' ') zfill(width)
x = "Pyhton"
x.center(10)
' Pyhton '
x.center(10,"?")
'??Pyhton??'
x.ljust(10)
'Pyhton '
x.rjust(10)
' Pyhton'
查找:
count(sub[ ,start[ ,end ]]):用于查找sub参数指定的子字符串在字符串中出现的次数
x = "pytnyotpnty"
x.count("y")
3
x.count("y", 0, 5)
2
find(sub[ ,start[ ,end ]]):寻找的是索引下标值(从左往右)
rfind(sub[ ,start[ ,end ]]):寻找的是索引下标值(从右往左)
index(sub[ ,start[ ,end ]]):找不到对相应的字符串则显示出异常,find会返回值-1
rindex(sub[ ,start[ ,end ]])同index(从右向左)
x.find("y")
1
x.rfind("y")
10
x.find("8")
-1
x.index("8")
Traceback (most recent call last):
File "<pyshell#96>", line 1, in <module>
x.index("8")
ValueError: substring not found
替换:
expandtabs([tabsize = 8]):空格替换Tab,返回新的字符串
code = """
print("i love Pyhton")
print("i love 建模")"""
new_code = code.expandtabs(0)
print(new_code)
print("i love Pyhton")
rint("i love 建模")
replace(old,new,count = -1):制定转换表格
"没有人比我更懂Pyhon233".replace("233","666")
'没有人比我更懂Pyhon666'
translate(table):制定转换表格
table = str.maketrans("ABCDEFG","1234567")
"Do you love Python?".translate(table)
'4o you love Python?'
#第三个参数为忽略句子中的各个字符的影响
table = str.maketrans("ABCDEFG","1234567","love")
"Do you love Python?".translate(table)
'4 yu Pythn?'
判断:
startswith(prefix[,start[,end]]):判断参数指定的子字符串是否出现在字符串的起始位置
endswith(suffix[,start[,end]]):
x.startswith("我")
True
x.endswith("on")
True
x.startswith("我",1)
False
x.startswith("爱",1)
True
x.endswith("py", 0 , 4)
False
x.endswith("Py", 0 , 4)
True
x = "她也喜欢Python"
if x.startswith(("你","我","她")):
print("总有人喜欢Python")
总有人喜欢Python
istitle:判断一单词均为大写字母开头,其余为小写
isupper:判断是否均为大写字母
islower:判断四否均为小写
isalpha:判断是否只有字母构成
#空格也不算字母
"I love Python".isalpha()
False
"IlovePython".isalpha()
True
isspace:判断是否为空白字符串
#转义字符也是空白字符
" \n".isspace()
True
isprintable:判断是否可以打印
#转义字符不可以打印
"I love Python\n".isprintable()
False
isidentifier:判断变量名是否是一个合法的标识符
"i love Python".isidentifier()
False
"i_love_Python".isidentifier()
True
"Python520".isidentifier()
True
"520Python".isidentifier()
False
iskeyword:判段是否是保留标志符
import keyword
keyword.iskeyword("if")
True
keyword.iskeyword("x")
False
截取:
strip(chars = None) lstrip(chars = None) rstrip(chars = None)
" 左侧不要留白".lstrip()
'左侧不要留白'
" 左右都不要留白 ".strip()
'左右都不要留白'
"www.python.com".lstrip("wcom.")
'python.com'
"www.python.cm".rstrip("wcom.")
'www.python'
"www.python.cm".strip("wcom.")
'python'
removeprefix(prefix):去掉前缀
removesuffix(suffix):去掉后缀
拆分&拼接:
partition(step)和 rpartition(sep)以参数指定的字符串为依据进行切割,并且将切割后的结果返回一个三个元素的元组
"www.python.com".partition(".")
('www', '.', 'python.com')
"www.python.com".rpartition(".")
('www.python', '.', 'com')
split(sep = None,maxsplit = -1),默认情况下切割空格,从左向右
rsplit(sep = None,maxsplit = 1),从右向左
splitlines(keepends = False),按行分割,将结果列表形式返回,图例不包含keepends
"www.python.com".split(".")
['www', 'python', 'com']
"www.python.com".split(".",1)
['www', 'python.com']
"www.python.com".rsplit(".",1)
['www.python', 'com']
"www\npython\ncom".split("\n")
['www', 'python', 'com']
"www\npython\ncom".splitlines()
['www', 'python', 'com']
"www\rpython\ncom".splitlines()
['www', 'python', 'com']
"www\r\npython\ncom".splitlines()
['www', 'python', 'com']
"www\r\npython\ncom".splitlines(True)
['www\r\n', 'python\n', 'com']
join(iterable):拼接
".".join(["www.","python",".com"]
'www..python..com'
#拼接时,利用元组或者列表表示都是可以的
"".join(["python","python"])
'pythonpython'
"".join(("python","python"))
'pythonpython'
格式化字符串的方法:
引入:
year = 2022
"现在是{}年".format(year)
'现在是2022年'
下标索引实现:
"1+2={},2的平方是{},3的立方是{}".format(1+2,2*2,3*3*3)
'1+2=3,2的平方是4,3的立方是27'
"{}看到{}就想敲代码".format("我","Python")
'我看到Python就想敲代码'
"{1}看到{0}就想敲代码".format("我","Python")
'Python看到我就想敲代码'
"{1}{1}{0}{0}".format("我","Python")
'PythonPython我我'
"{谁}看到{编程语言}就想敲代码".format(谁 = "我",编程语言 = "Python")
'我看到Python就想敲代码'
"{0}爱{编程语言},爱{编程语言}的人运气都不会太差".format("我",编程语言 = "Python")
'我爱Python,爱Python的人运气都不会太差'
[[fill]align][sign][#][0][width][grouping_option][.precision][type]
align指的是对其的方式:
"{},{},{}".format(1, {}, 2)
'1,{},2'
"{},{{}},{}".format(1, 2)
'1,{},2'
"{:^10}".format(250)
' 250 '
#索引
"{1:>10}{0:<10}".format(520,250)
' 250520 '
"{left:>10}{right:<10}".format(right = 520,left = 250)
' 250520 '
[0] 此处0是正在从指定的宽度前面添加的,表示为数字类型启用感知正负号的0填充效果。例如:
"{:010}".format(520)
'0000000520'
"{:010}".format(-520)
'-000000520'
也可以填充字符:
"{1:%>10}{0:%<10}".format(520,250)
'%%%%%%%250520%%%%%%%'
"{:0=10}".format(520)
'0000000520'
"{:0=10}".format(-520)
'-000000520'
符号选项:
"{:+}{:-}".format(520,-250)
'+520-250'
分隔符:
"{:,}".format(1234)
'1,234'
"{:_}".format(1234)
'1_234'
#如果位数不足千位的分隔符是不显示的
"{:,}".format(123)
'123'
"{:,}".format(123456789)
'123,456,789'
类型 [ Type ]
"{:.2f}".format(3.1415)
'3.14'
"{:.2g}".format(3.1415)
'3.1'
"{:.6}".format(3.1415)
'3.1415'
"{:.6}".format("i love Python")
'i love'
#不可以是文字或者数字
"{:.2}".format(520)
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
"{:.2}".format(520)
ValueError: Precision not allowed in integer format specifier
整数进制:
"{:b}".format(80)
'1010000'
"{:c}".format(80)
'P'
"{:d}".format(80)
'80'
"{:o}".format(80)
'120'
"{:x}".format(80)
'50'
#其中类型前面+ “ * ”号输出时也带有进制
"{:#b}".format(80)
'0b1010000'
"{:#x}".format(80)
'0x50'
小数或负数 的表示:
示例如下:
"{:g}".format(1234.5678)
'1234.57'
"{:g}".format(12345678)
'1.23457e+07'
"{:%}".format(0.98)
'98.000000%'
"{:0.2%}".format(0.98)
'98.00%'
也可通过关键字参数设定值 :
"{:.{prec}f}".format(3.1415,prec = 2)
'3.14'
"{:{fill}{align}{width}.{prec}{ty}}".format(3.1415,fill="+",align="^",width=10,prec=3,ty="g")
'+++3.14+++'
f 字符串 (3.6版本以上)
f"1+2={1+2},2的平方是{2*2},3的立方是{3*3*3}"
'1+2=3,2的平方是4,3的立方是27'
f"{-520:010}"
'-000000520'
f"{123456789:,}"
'123,456,789'
fill = "+"
align = "^"
width = 10
prec = 3
ty = "g"
"{3.1415:{fill}{align}{width}.{prec}{ty}}"
'+++3.14+++'