详解Python数值、字符串处理
本文目录
数值数据类型
数值运算
数值运算举例
单引号双引号区别 反斜杠 \ 转义符 输出原始字符串 三引号
操作字符串
字符串修改
索引
乘法
拼接
in成员资格检查
遍历
求长度
字符串方法
find方法
join方法
split方法
lower方法
upper方法
replace方法
strip,lstrip和rstrip方法
translate方法
startswith方法
endswith方法
is开头的诸多方法
字符串格式化输出:format方法
调用参数
参数格式转换
python指定字符宽度,精度
指定字符千分位分隔符
对齐
指定填充字符
等号(=),指定将填充字符放在符号和数字之间
3、参考资料
正文开始啦
1、数值
数值数据类型
python支持如下数值型数据:
数值类型 实例
整数(int) 0, -3
浮点数(float) 3.1415926, 0.3E+1, 3E-1
十六进制(hexadecimal) 0xAF(以0x开头,其后都是数字或者大小写字母)
八进制(octal) 0o10(以0o或0O开头,其后其后都是0-7之间的整数)
二进制(binary) 0b1011010010(以0b或0B开头,其后都是0、1)
数值运算
常见数字运算类型及内置函数如下:
运算符 含义
+ (加)
- (减)
* (乘)
/ (除)
// (整除运算)
% (求余数)
** (幂)
int(x) (取x整数部分)
float(x) (将x转化为浮点数)
pow(x,y) (求x的y次幂)
abs(x) (求x的绝对值)
round(x) (x四舍五入)
bin(x) (将x转化为二进制)
oct(x) (将x转化为八进制)
hex(x) (将x转化为十六进制)
math.floor(x) (math模块中向下取整,floor中文有地板的意思)
math.ceil(x) (math模块中向上取整,ceil中文天花板的意思)
数值运算举例
In [1]: #加
...: print(2 + 3)
5
In [2]: #减
...: print(2 - 3)
-1
In [3]: #乘
...: print(2 * 3)
6
In [4]: #除
...: print(2 / 3)
0.6666666666666666
In [5]: #整除运算,向下取整
...: print(1 // 3)
...: print(5.0 // 2.0)#输出结果类型与除数和被除数一致
...: print(5.0 // 2)
...: print(5 // 2.0)
...: print(-5 // 2)#向下(向负3)取整
0
2.0
2.0
2.0
-3
In [6]: #求余运算
...: print(5 % 2)
...: print(5.0 % 2.0)
...: print(5.0 % 2)
...: print(5 % 2.0)
1
1.0
1.0
1.0
In [7]: #求幂
...: print(2 ** 3)
...: print(-2 ** 2)#注意比较区别
...: print((-2) ** 2)
8
-4
4
In [8]: #取浮点数
...: print(float(2))
...:
...:
2.0
In [9]: #取整数
...: print(int(2.3))
2
In [10]: #取浮点数
...: print(float(2))
2.0
In [11]: #pow函数求幂
...: print(pow(2,3))
...: print(2 ** 3)#与上行等价
8
8
In [12]: #取绝对值
...: print(abs(-2))
2
In [13]: #四舍五入
...: print(round(2.3))
...: print(round(2.6))
2
3
In [14]: #转二进制
...: print(bin(2))
...:
...: #转八进制
...: print(oct(2))
...:
...: #转十六进制
...: print(hex(2))
0b10
0o2
0x2
In [15]: #向下取整和向上取整
...: import math
...: print(math.floor(3.5))#向下取整
...: print(math.ceil(3.5))#向上取整
3
4
字符串使用单引号,双引号或者三引号包围起来,例如,"hello, boy!",'hello, boy!','''hello,boy!'''。
单引号双引号区别
In [16]: #该场景单引号和双引号作用一致
...: print("hello boy!")
...: print('hello girl!')
hello boy!
hello girl!
#以下场景双引号和单引号作用不一致
In [13]: print('hello,boy! Let's do it')
File "<ipython-input-13-be7bb4cf818c>", line 1
print('hello,boy! Let's do it')
^
SyntaxError: invalid syntax
反斜杠 \ 转义符
In [15]: print('hello,boy! Let\'s do it')
hello,boy! Let's do it
输出原始字符串
输出字符串例如,换行符(\n),tab分隔符(\t)等的原始字符串,而不是换行或者tab分割。
In [16]: #方法一,反斜线转义
...: #分别在特殊字符钱加反斜线转义
...: print("Hi\\tHello\\nboy!")
...:
...: #方法二,使用r
...: print(repr("Hi\tHello\nboy!"))
...: print(r"Hi\tHello\nboy!")
Hi\tHello\nboy!
Hi\tHello\nboy!
三引号
In [26]: print("""Hello
...: ,
...: boy!""")
Hello
,
boy!
In [22]: print("""hello,boy! Let's d"o it""")
hello,boy! Let's d"o it
操作字符串
索引、切片、乘法、成员资格检查、长度、最小值和最大值都适用于字符串。
字符串修改
In [128]: "Hello"[1:]="o"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-128-0a82fa2a7175> in <module>
----> 1 "Hello"[1:]="o"
TypeError: 'str' object does not support item assignment
索引
索引每次取一个元素,python索引从0开始,可以为负数,最后一位索引为-1,倒数第二位索引为-2,依次类推。
In [6]: "Keepstudying"[0:3]#取出索引位为0到2的元素
Out[6]: 'Kee'
In [7]: "Keepstudying"[0:-2]#取出索引位为0到倒数第三个元素
Out[7]: 'Keepstudyi'
In [8]: "Keepstudying"[-4:-2]#取出索引位为-4到-3的元素
Out[8]: 'yi'
In [9]: "Keepstudying"[:3]#第一个参数可以省略
Out[9]: 'Kee'
In [10]: "Keepstudying"[:]#取出所有元素
Out[10]: 'Keepstudying'
In [11]: "Keepstudying"[1:]#第二个参数也可以省略
Out[11]: 'eepstudying'
In [13]: "Keepstudying"[1:5:2]#步长为2
Out[13]: 'ep'
In [14]: "Keepstudying"[::-1]#将字符颠倒
Out[14]: 'gniydutspeeK'
乘法
In [27]: print("Keepstudying\t" * 10)#重复10次
Keepstudying Keepstudying Keepstudying Keepstudying Keepstudying Keepstudying Keepstudying Keepstudying Keepstudying Keepstudying
拼接
使用加号拼接。
In [27]: print("Hello,"+"world!")
Hello,world!
in成员资格检查
使用in判断字符串是否包含某个子字符串,包含返回True,不包含返回False。
In [15]: "stu" in "Keepstudying"
Out[15]: True
In [16]: "stv" in "Keepstudying"
Out[16]: False
遍历
依次输出字符串中每个元素。
In [18]: for i in "Keepstudying":
...: print(i)
K
e
e
p
s
t
u
d
y
i
n
g
求长度
In [23]: len("Keepstudyin \t\ng")
Out[23]: 16
字符串方法
In [23]: print(dir(str))#dir列出字符串所用方法
['__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', 'isascii', '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']
find方法
语法,str.find(sub_str,a,b)
字符串str中查找子字符串sub_str所在位置时使用,a,b分别制定从str中开始搜索的位置,默认从第一个字符开始,a,b均可忽略;如果找到sub_str,就返回sub_str的第一个字符的索引,没找到返回-1。可用来判断str中是否包sub_str以及位置。
In [32]: print("xiyangyang lanyangyang".find("huitanglang"))
-1
In [33]: print("xiyangyang lanyangyang".find("yang"))
2
join方法
In [36]: print("+".join("xiyangyang"))
x+i+y+a+n+g+y+a+n+g
split方法
语法:str.split(sep),以sep为分隔符,拆分字符串str为一个list。
In [37]: print("x+i+y+a+n+g+y+a+n+g".split("+"))
['x', 'i', 'y', 'a', 'n', 'g', 'y', 'a', 'n', 'g']
lower方法
语法:str.lower(),将字符串str转化为小写版本。
In [39]: print("Hello! Hi!".lower())
hello! hi!
upper方法
In [41]: print("Hello! Hi!".upper())
HELLO! HI!
replace方法
语法:str.replace("sub_str1", "sub_str2", max)。将字符串str中的子字符串sub_str1替换为sub_str2,max为允许替换的最大次数,可忽略,默认替换所有。
In [48]: print("xiyangyang lanyangyang".replace("an","XX",2))
xiyXXgyXXg lanyangyang
strip,lstrip和rstrip方法
语法:三个方法类似,str.strip(sub_str)。strip方法去掉str开头和结尾的子字符串sub_str,sub_str可忽略,默认为空格。
In [49]: print(" Hello ".strip())
Hello
In [50]: print(" Hello ".lstrip())
Hello
In [51]: print(" Hello ".rstrip())
Hello
In [52: print(" Hello ".rstrip("o "))
Hell
translate方法
语法:str.translate(table),该方法同时替换str中多个字符,replace一次只能替换一个。
In [56]: old = "axy"
...: new = "123"
...: #调用字符串str的maketrans方法制作转换表
...: table = str.maketrans(old, new)
...:
...: str1 = "xiyangyang lanyangyang"
...: print (str1.translate(table))
2i31ng31ng l1n31ng31ng
startswith方法
语法:str.startswith(sub_str, a, b)。判断str是否以sub_str开头,是则返回True,否则返回False,a,b指定检索开始和结束( 默认是字符串的长度,表示结束搜索的位置)为止,默认从第一个字符开始。
In [64]: print("Hello".startswith("H"))
True
endswith方法
使用类似startswith,判断str是否以sub_str结尾。
is开头的诸多方法
'isalnum', 'isalpha', 'isascii', 'isdecimal',
'isdigit', 'isidentifier', 'islower', 'isnumeric',
'istitle', 'isupper'
字符串格式化输出:format方法
调用参数
按顺序将字段和参数配对输出
#按顺序将字段和参数配对输出
In [79]: "{} {} {} {}".format(1, 2, 4, 3)
Out[79]: '1 2 4 3'
#给参数指定名称,通过参数名称调用输出
In [80]: "{a} {a} {b} {b}".format(a=1, b=2)
Out[80]: '1 1 2 2'
#以上两种方法混用
In [81]: "{} {a} {} {b}".format(0, 3, a=1, b=2)
Out[81]: '0 1 3 2'
#未命名参数通过索引调用输出
In [82]: "{1} {a} {0} {b}".format(0, 3, a=1, b=2)
Out[82]: '3 1 0 2'
参数格式转换
指定要转换的值是哪种类型,如下例中的f b。
In [85]: "The number is {:f}".format(42)#f将小数表示为定点数
Out[85]: 'The number is 42.000000'
In [86]: "The number is {:b}".format(42)#b将整数表示为二进制数
Out[86]: 'The number is 101010'
python指定字符宽度,精度
常用转化类型
b 将整数表示为二进制数
c 将整数解读为Unicode码点
d 将整数视为十进制数进行处理,这是整数默认使用的说明符
e 使用科学表示法来表示小数(用e来表示指数)
E 与e相同,但使用E来表示指数
f 将小数表示为定点数
F 与f相同,但对于特殊值(nan和inf),使用大写表示
g 自动在定点表示法和科学表示法之间做出选择。这是默认用于小数的说明符,但在默认情况下至少有1位小数
G 与g相同,但使用大写来表示指数和特殊值
n 与g相同,但插入随区域而异的数字分隔符
o 将整数表示为八进制数
s 保持字符串的格式不变,这是默认用于字符串的说明符
x 将整数表示为十六进制数并使用小写字母
X 与x相同,但使用大写字母
% 将数表示为百分比值(乘以100,按说明符f设置格式,再在后面加上%)
In [96]: "Pi is {pi:10.2f}".format(pi=math.pi)#指定字符快读为10,精度为2个小数位
Out[96]: 'Pi is 3.14'
指定字符千分位分隔符
In [101]: 'Oh gold banknote is {:,} yuan'.format(100000000000)
Out[101]: 'Oh gold banknote is 100,000,000,000 yuan'
对齐
分别使用<、>和^指定左对齐,右对齐和居中。
In [107]: print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(math.pi))
指定填充字符
默认为空格
In [113]: print('{0:$<10.2f}\n{0:@^10.2f}\n{0:&>10.2f}'.format(math.pi))
3.14$$$$$$
@@@3.14@@@
&&&&&&3.14
等号(=),指定将填充字符放在符号和数字之间。
此处=类似于<、>和^
In [127]: print('{0:$>10.2f}\n{1:$=10.2f}'.format(math.pi, -math.pi))
$$$$$$3.14
-$$$$$3.14
3、参考资料
https://www.cnblogs.com/f-ck-need-u/p/9127699.html#21-isalphaisdecimalisdigitisnumericisalnum
https://docs.python.org/zh-cn/3.7/library/stdtypes.html#str.join
-END-
👇点击阅读更多👇 关注「pythonic生物人」 加微信群:扫码备注学习 |