Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

python - dropping trailing '.0' from floats

I'm looking for a way to convert numbers to string format, dropping any redundant '.0'

The input data is a mix of floats and strings. Desired output:

0 --> '0'

0.0 --> '0'

0.1 --> '0.1'

1.0 --> '1'

I've come up with the following generator expression, but I wonder if there's a faster way:

(str(i).rstrip('.0') if i else '0' for i in lst)

The truth check is there to prevent 0 from becoming an empty string.

EDIT: The more or less acceptable solution I have for now is this:

('%d'%i if i == int(i) else '%s'%i for i in lst)

It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See PEP 3101:

'g' - General format. This prints the number as a fixed-point
      number, unless the number is too large, in which case
      it switches to 'e' exponent notation.

Old style (not preferred):

>>> "%g" % float(10)
'10'

New style:

>>> '{0:g}'.format(float(21))
'21'

New style 3.6+:

>>> f'{float(21):g}'
'21'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...