如何改进这个简单的代码块 [英] how to improve this simple block of code

查看:59
本文介绍了如何改进这个简单的代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有...

x =" 132.00"


但是我想把它显示为132。 ...删除尾随

零...我目前正在尝试这个


如果x.endswith(0):

x = x [:len(x)-1]

如果x.endswith(" 0"):

x = x [:len(x) - 1]

if x.endswith("。"):

x = x [:len(x)-1]


我是这样做的,因为如果

x =" 132.15" ...我不想修改它。但是如果

x =" 132.60" ...我希望它成为132.6


有更好的方法吗?对我来说似乎有点难看。


TIA

(提前谢谢)

解决方案

py写道:

说我有...
x =" 132.00"

但我会喜欢将其显示为132。 ...删除尾随的
零...我现在尝试这个

如果x.endswith(0):
x = x [:len(x) -1]
如果x.endswith(" 0"):
x = x [:len(x)-1]
如果x.endswith("。"):
x = x [:len(x)-1]

我是这样做的,因为如果
x =" 132.15" ...我不想修改它。但是如果
x =" 132.60" ...我希望它成为132.6

有更好的方法吗?对我来说似乎有点难看。

TIA
(提前谢谢)




x = x.rstrip(''0 '')#删除尾随零

x = x.rstrip(''。'')#删除尾随点


或组合:


x = x.rstrip(''0。'')#删除尾随的零和点


hanz写道:

或合并:

x = x.rstrip(''0。'')#删除尾随零和点

< br>

" 130.00" .rstrip(" 0.")



''13''


哎呀。


彼得


Say I have...
x = "132.00"

but I''d like to display it to be "132" ...dropping the trailing
zeros...I currently try this

if x.endswith("0"):
x = x[:len(x)-1]
if x.endswith("0"):
x = x[:len(x)-1]
if x.endswith("."):
x = x[:len(x)-1]

I do it like this because if
x = "132.15" ...i dont want to modify it. But if
x = "132.60" ...I want it to become "132.6"

is there a better way to do this? It seems a bit ugly to me.

T.I.A
(thanks in advance)

解决方案

py wrote:

Say I have...
x = "132.00"

but I''d like to display it to be "132" ...dropping the trailing
zeros...I currently try this

if x.endswith("0"):
x = x[:len(x)-1]
if x.endswith("0"):
x = x[:len(x)-1]
if x.endswith("."):
x = x[:len(x)-1]

I do it like this because if
x = "132.15" ...i dont want to modify it. But if
x = "132.60" ...I want it to become "132.6"

is there a better way to do this? It seems a bit ugly to me.

T.I.A
(thanks in advance)



x = x.rstrip(''0'') # removes trailing zeros
x = x.rstrip(''.'') # removes trailing dot(s)


Or combined:

x = x.rstrip(''0.'') # removes trailing zeroes and dots


hanz wrote:

Or combined:

x = x.rstrip(''0.'') # removes trailing zeroes and dots


"130.00".rstrip("0.")


''13''

Oops.

Peter


这篇关于如何改进这个简单的代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆