本文目錄一覽:
- 1、Python 提取字元串中固定長度的數字串,並在下一列輸出
- 2、Python中如何輸入一段文字,輸出文字的長度,然後按倒敘方式輸出?
- 3、python 如何控制輸出的小數長度?
- 4、python.怎樣輸出長度為110的字元串?
Python 提取字元串中固定長度的數字串,並在下一列輸出
import re
def findit(matchstr,searchstr):
Li=[] #找到的匹配字串置於Li列表中
rs=re.search(matchstr,searchstr)
while rs!=None:
Li=Li+list(rs.groups())
searchstr=searchstr[rs.span()[1]:]
rs=re.search(matchstr,searchstr)
return Li
def main():
matchstr=r'(\d{16})’ #正則表達式 匹配16個數字
#以下是要查找字串的例子
searchstr=’2018060512345678hekoedfk2018070612345678fifjr1234567890123456dfsdf’
#在字串searchstr中找到的匹配數字都在rs這個list中
rs=findit(matchstr,searchstr)
for x in rs:
print(x)
#mystri=’/’.join(rs) #生成以/分隔的數字串
#print(mystri) #輸出以/分隔的數字串
main()
Python中如何輸入一段文字,輸出文字的長度,然後按倒敘方式輸出?
from time import *
def fun(line):
for i in range(len(line)):
print(“\r” + line[0:i+1], end = “”)
sleep(1)
python 如何控制輸出的小數長度?
Python裡面小數點長度精度控制方法:
一、要求較小的精度
將精度高的浮點數轉換成精度低的浮點數。
1.round()內置方法
這個是使用最多的,剛看了round()的使用解釋,也不是很容易懂。round()不是簡單的四捨五入的處理方式。
For the built-in types supporting round(), values are rounded to the
closest multiple of 10 to the power minus ndigits; if two multiples are equally
close, rounding is done toward the even choice (so, for example, both round(0.5)
and round(-0.5) are 0, and round(1.5) is 2).
round(2.5)
2
round(1.5)
2
round(2.675)
3
round(2.675, 2)
2.67
round()如果只有一個數作為參數,不指定位數的時候,返回的是一個整數,而且是最靠近的整數(這點上類似四捨五入)。但是當出現.5的時候,兩邊的距離都一樣,round()取靠近的偶數,這就是為什麼round(2.5)
=
2。當指定取捨的小數點位數的時候,一般情況也是使用四捨五入的規則,但是碰到.5的這樣情況,如果要取捨的位數前的小樹是奇數,則直接捨棄,如果偶數這向上取捨。看下面的示例:
round(2.635, 2)
2.63
round(2.645, 2)
2.65
round(2.655, 2)
2.65
round(2.665, 2)
2.67
round(2.675, 2)
2.67
2. 使用格式化
效果和round()是一樣的。
a = (“%.2f” % 2.635)
a
‘2.63’
a = (“%.2f” % 2.645)
a
‘2.65’
a = int(2.5)
a
2
二、要求超過17位的精度分析
python默認的是17位小數的精度,但是這裡有一個問題,就是當我們的計算需要使用更高的精度(超過17位小數)的時候該怎麼做呢?
1. 使用格式化(不推薦)
a = “%.30f” % (1/3)
a
‘0.333333333333333314829616256247’
可以顯示,但是不準確,後面的數字往往沒有意義。
2. 高精度使用decimal模塊,配合getcontext
from decimal import *
print(getcontext())
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero,
Overflow])
getcontext().prec = 50
b = Decimal(1)/Decimal(3)
b
Decimal(‘0.33333333333333333333333333333333333333333333333333’)
c = Decimal(1)/Decimal(17)
c
Decimal(‘0.058823529411764705882352941176470588235294117647059’)
float(c)
0.058823529411764705
默認的context的精度是28位,可以設置為50位甚至更高,都可以。這樣在分析複雜的浮點數的時候,可以有更高的自己可以控制的精度。其實可以留意下context裡面的這rounding=ROUND_HALF_EVEN
參數。ROUND_HALF_EVEN, 當half的時候,靠近even.
三、關於小數和取整
既然說到小數,就必然要說到整數。一般取整會用到這些函數:
1. round()
這個不說了,前面已經講過了。一定要注意它不是簡單的四捨五入,而是ROUND_HALF_EVEN的策略。
2. math模塊的ceil(x)
取大於或者等於x的最小整數。
3. math模塊的floor(x)
去小於或者等於x的最大整數。
from math import ceil, floor
round(2.5)
2
ceil(2.5)
3
floor(2.5)
2
round(2.3)
2
ceil(2.3)
3
floor(2.3)
2
python.怎樣輸出長度為110的字元串?
Python對字元串長度沒有明確限制,檢查下你的上下文,是不是有做了什麼截斷操作
祝好運,望採納
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/194675.html