且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python语言学习之数值、小数、空格那些事:python和数值、小数、空格的使用方法之详细攻略

更新时间:2022-05-31 04:01:36

Python与数值那些事


1、python保留两位小数/保留小数点位数


#1、对于浮点数

a = 3.1415

b = 3.016

print(round(a,2), round(b,2))

print('%.2f' % a, '%.2f' % b)        

print(float('%.2f' % a), float('%.2f' % b))

3.14 3.02

3.14 3.02

3.14 3.02

#2、对于整数

from decimal import Decimal

a=1

a=Decimal(a).quantize(Decimal('0.00'))

print(a)    #结果1.00

#3、通用方法

a=1

a=("%.2f" % a)

print(a)    #结果1.00


Python去掉空格的方法


#去除空格的方法

data="    我爱 区  块   链技术,ML技术    "

Remove_space01=data.strip()          #把头和尾的空格去掉

Remove_space02=data.lstrip()         #把左边的空格去掉

Remove_space03=data.rstrip()         #把右边的空格去掉

Remove_space04=data.replace(' ','')  #replace('c1','c2') 把字符串里的c1替换成c2

Remove_space05=data.split(data)      #通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串

import re

Remove_space06=re.split(r'\s+', 'a b   c')  #采用正则表达式

print(Remove_space01,"\n",Remove_space02,"\n",Remove_space03,"\n",Remove_space04,"\n",Remove_space05,"\n",Remove_space06)

我爱 区  块   链技术,ML技术

我爱 区  块   链技术,ML技术    

    我爱 区  块   链技术,ML技术

我爱区块链技术,ML技术

['', '']

['a', 'b', 'c']