【问题标题】:Converting integer to string in Python在 Python 中将整数转换为字符串
【发布时间】:2010-10-31 23:45:31
【问题描述】:

我想在 Python 中将整数转换为字符串。我徒劳地打字:

d = 15
d.str()

当我尝试将其转换为字符串时,它会显示一个错误,例如 int 没有任何名为 str 的属性。

【问题讨论】:

  • 对于这些类型的转换,一个好的解决方案是使用像converttypes.com 这样的网站,您可以在其中查看几乎所有编程语言的所有转换。

标签: python string integer


【解决方案1】:

试试这个:

str(i)

【讨论】:

    【解决方案2】:
    >>> str(10)
    '10'
    >>> int('10')
    10
    

    文档链接:

    转成字符串是通过内置的str()函数完成的,它基本上调用了其参数的__str__()方法。

    【讨论】:

      【解决方案3】:
      >>> i = 5
      >>> print "Hello, world the number is " + i
      TypeError: must be str, not int
      >>> s = str(i)
      >>> print "Hello, world the number is " + s
      Hello, world the number is 5
      

      【讨论】:

        【解决方案4】:

        Python 中没有类型转换和类型强制。您必须以显式方式转换您的变量。

        要转换字符串中的对象,请使用str() 函数。它适用于任何定义了名为__str__() 的方法的对象。其实

        str(a)
        

        等价于

        a.__str__()
        

        如果您想将某些内容转换为 int、float 等,则相同。

        【讨论】:

        • 这个解决方案帮助了我,我正在将字母数字字符串转换为数字字符串,用它们的 ascii 值替换字母,但是直接使用 str() 函数不起作用,但 __str__() 起作用。示例(python2.7); s = "14.2.2.10a2" 非工作代码: print "".join([ str(ord(c)) if (c.isalpha()) else c for c in s ]) 工作代码: print "".join ([ ord(c).__str__() if (c.isalpha()) else c for c in s ]) 预期输出:14.2.2.10972
        【解决方案5】:

        管理非整数输入:

        number = raw_input()
        try:
            value = int(number)
        except ValueError:
            value = 0
        

        【讨论】:

          【解决方案6】:

          我认为最体面的方式是``。

          i = 32   -->    `i` == '32'
          

          【讨论】:

          【解决方案7】:

          您可以使用%s.format

          >>> "%s" % 10
          '10'
          >>>
          

          或者:

          >>> '{}'.format(10)
          '10'
          >>>
          

          【讨论】:

            【解决方案8】:

            对于想要将 int 转换为特定数字的字符串的人,建议使用以下方法。

            month = "{0:04d}".format(localtime[1])
            

            更多细节可以参考 Stack Overflow 问题Display number with leading zeros

            【讨论】:

              【解决方案9】:

              在 Python => 3.6 中,您可以使用f 格式:

              >>> int_value = 10
              >>> f'{int_value}'
              '10'
              >>>
              

              【讨论】:

                【解决方案10】:

                随着f-strings 在 Python 3.6 中的引入,这也将起作用:

                f'{10}' == '10'
                

                它实际上比调用str() 更快,但以可读性为代价。

                其实比%x字符串格式化和.format()快!

                【讨论】:

                  【解决方案11】:

                  对于 Python 3.6,您可以使用 f-strings 新功能转换为字符串,与 str() 函数相比,它更快。它是这样使用的:

                  age = 45
                  strAge = f'{age}'
                  

                  出于这个原因,Python 提供了 str() 函数。

                  digit = 10
                  print(type(digit)) # Will show <class 'int'>
                  convertedDigit = str(digit)
                  print(type(convertedDigit)) # Will show <class 'str'>
                  

                  更详细的答案可以查看这篇文章:Converting Python Int to String and Python String to Int

                  【讨论】:

                    【解决方案12】:

                    这是一个更简单的解决方案:

                    one = "1"
                    print(int(one))
                    

                    输出控制台

                    >>> 1
                    

                    在上面的程序中,int()用来转换一个整数的字符串表示形式。

                    注意:字符串格式的变量只有在变量完全由数字组成时才能转换为整数。

                    同理,str()用于将整数转换为字符串。

                    number = 123567
                    a = []
                    a.append(str(number))
                    print(a) 
                    

                    我使用了一个列表来打印输出以突出显示变量 (a) 是一个字符串。

                    输出控制台

                    >>> ["123567"]
                    

                    但要了解列表存储字符串和整数的区别,请先查看以下代码,然后再查看输出。

                    代码

                    a = "This is a string and next is an integer"
                    listone=[a, 23]
                    print(listone)
                    

                    输出控制台

                    >>> ["This is a string and next is an integer", 23]
                    

                    【讨论】:

                    • 请问我的文章有用吗?
                    【解决方案13】:

                    在python中有几种方法可以将整数转换为字符串。 您可以使用 [ str(integer here) ] 函数、f-string [ f'{integer here}']、.format()function [ '{}'.format(integer here) 甚至 '%s' % 关键字 [此处为 '%s'% 整数]。所有这些方法都可以将整数转换为字符串。

                    见下例

                    #Examples of converting an intger to string
                    
                    #Using the str() function
                    number = 1
                    convert_to_string = str(number)
                    print(type(convert_to_string)) # output (<class 'str'>)
                    
                    #Using the f-string
                    number = 1
                    convert_to_string = f'{number}'
                    print(type(convert_to_string)) # output (<class 'str'>)
                    
                    #Using the  {}'.format() function
                    number = 1
                    convert_to_string = '{}'.format(number)
                    print(type(convert_to_string)) # output (<class 'str'>)
                    
                    #Using the  '% s '% keyword
                    number = 1
                    convert_to_string = '% s '% number
                    print(type(convert_to_string)) # output (<class 'str'>)
                    
                    
                    

                    【讨论】:

                      猜你喜欢
                      • 2010-12-27
                      • 1970-01-01
                      • 2013-02-18
                      • 1970-01-01
                      • 2015-09-25
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多