• 技术文章 >常见问题 >Python常见问题

    Python中实现float转为String

    宋雪维宋雪维2020-12-31 15:11:53原创29321

    之前向大家介绍过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

    输出

    <class 'float'>
    <class 'str'>

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

    专题推荐:python float转str
    品易云
    上一篇:Python中int与bytes相互转换 下一篇:Python中生成九九乘法表的方法有哪几种?

    相关文章推荐

    • python id()函数是什么• ​Python中complex函数是什么?• python中如何用complex函数取出实数部分?• Python中数值类型有哪几种?• 如何在Python中取整?• python中的int函数如何使用?• Python中int与bytes相互转换• Python中float() 函数是如何实现的?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网