我有一些当前设置为运行一组方程的代码。我想允许输入自定义数字序列。我不想输入100,而是想输入1 + 00,但是我希望代码将其解释为100。等式运行之后,我希望代码以X + XX格式返回结果。 / p>
我是编码的新手(这是我的第一部分代码),并且四处寻找试图格式化它的方法。我知道在excel中我可以指定“#+ ##。00”的自定义数字格式,以使其以我需要的格式输出单元格。我一直找不到对应的python。
from tkinter import *
from math import *
def show_entry_fields():
try:
a, c, d, e, = float(e1.get()), float(e3.get()), float(e4.get()), float(e5.get())
b = e - d
s = (a + b + c) / 2
height = (sqrt (s * (s - a) * (s - b) * (s - c)) * 2) / b
height = float(format(height, '.3f'))
height_label['text'] = str(height)
side =((sqrt ((a ** 2) - (height ** 2))) + b)
side = float(format(side, '.3f'))
side_label['text'] = str(side)
except ValueError:
pass
master.after(100, show_entry_fields)
master = Tk()
master.attributes("-topmost", True)
master.title("Triangulation Plotting")
Label(master, text="Measurement #1 Station Line Location").grid(row=1, column=0, sticky=W, pady=4)
e4 = Entry(master)
e4.grid(row=1, column=1, sticky=E)
Label(master, text="Triangulation Measurement #1").grid(row=2, column=0, sticky=W, pady=4)
e1 = Entry(master)
e1.grid(row=2, column=1, sticky=E)
Label(master, text="Measurement #2 Station Line Location").grid(row=3, column=0, sticky=W, pady=4)
e5 = Entry(master)
e5.grid(row=3, column=1, sticky=E)
Label(master, text="Triangulation Measurement #2").grid(row=7, column=0, sticky=W, pady=4)
e3 = Entry(master)
e3.grid(row=7, column=1, sticky=E, pady=4)
Label(master, text="Offset from station line").grid(row=8, column=0, sticky=W, pady=4)
height_label = Label(master, text="")
height_label.grid(row=8, column=1)
Label(master, text="Measurement on Station Line").grid(row=9, column=0, sticky=W, pady=4)
side_label = Label(master, text="")
side_label.grid(row=9, column=1)
master.after(100,show_entry_fields)
master.mainloop()
省略的部分是输入字段。数学和一切都完全按需要列出。 X + XX的条目是用于特定用途的格式。我查看了docs下的str.format(),但看不到该怎么做。
编辑: 因此,如果我输入2 + 66,它将被解释为266。它将基于其他输入进行计算,并且结果将以相同的格式显示。对于小于100或1 + 00的数字,它将输出以0开头的0,即57的0 + 57。输入和结果将以浮点数表示。所有结果将加载到小数点后2位。
答案 0 :(得分:0)
对于字符串,在true
和'+'
上分割,用f字符串构造一个数字;把它变成一个浮子然后把它弄圆。对于浮点数,将其舍入到所需的精度,将其转换为字符串,在'.'
上分割,然后使用f字符串构造。
'.'
f-strings所需的Python 3.6
对于Python 3.5-使用字符串格式:
def convert(thing):
if isinstance(thing, str):
a,b = thing.split('+')
b,*d = b.split('.')
d = '00' if not d else d[0]
thing = round(float(f'{a}{b}.{d}'), 2)
elif isinstance(thing, (int,float)):
thing = str(round(thing, 2))
thing,*d = thing.split('.')
d = '00' if not d else d[0]
thing = thing if len(thing) > 2 else '0'+thing
thing = f'{thing[:-2]}+{thing[-2:]}.{d}'
return thing
用法
字符串到数字:
thing = round(float('{}{}.{}'.format(a,b,d)), 2)
# and
thing = '{}+{}.{}'.format(thing[:-2],thing[-2:],d)
数字转换为字符串
>>> convert('2+66')
266.0
>>> convert('0+22')
22.0
>>> convert('2+66') + convert('0+22')
288.0
>>> x = '223+56.666'
>>> convert(x)
22356.67
>>> y = '-54+22.33212'
>>> convert(y)
-5422.33
>>>