Python中如何实现float转为String?


之前向大家介绍过Python中float() 函数的实现过程(https://www.py.cn/jishu/jichu/21933.html)。在使用float() 函数时,我们用的字符是浮点数,但是有时我们并不需要浮点数,这时我们就要将float转化为其他形式。本文将介绍Python float 转换为 String的两种方法:使用'%d'%num实现和使用str()方法实现。

方法一:使用'%d'%num实现

num = 322

str1 = '%d'%num      # 转为整型

print(str1)

>>>

'32'

num = 32.348

str2 = '%f'%32.348   # 转为浮点型

print(str2)

>>>

'32.348000'

  输出方法二:使用str()方法实现

pi = 3.1415

  

print(type(pi))  # float

  

piInString = str(pi)  # float -> str

  

print(type(piInString))  # str

  以上就是Python中将float 转换为 String的两种方法,都是很简单的方法,大家可以选择喜欢喜欢的方法进行转换哦

原文至:https://www.py.cn/faq/python/21936.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM