在Python中将整数转换为字符串

发布于 2024-07-23 03:57:35 字数 348 浏览 5 评论 0原文

如何将整数转换为字符串?

42   ⟶   "42"

相反,请参阅如何将字符串解析为浮点数或整数?。 浮点数可以类似地处理,但处理小数点可能很棘手,因为浮点值不精确。 有关更具体的建议,请参阅将浮点数转换为字符串而不进行舍入

How do I convert an integer to a string?

42   ⟶   "42"

For the reverse, see How do I parse a string to a float or int?. Floats can be handled similarly, but handling the decimal points can be tricky because floating-point values are not precise. See Converting a float to a string without rounding it for more specific advice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

不爱素颜 2024-07-30 03:57:35
>>> str(42)
'42'

>>> int('42')
42

文档链接:

str(x) 通过调用 x.__str__(),或 repr(x) 如果 x 没有 __str__() 方法。

>>> str(42)
'42'

>>> int('42')
42

Links to the documentation:

str(x) converts any object x to a string by calling x.__str__(), or repr(x) if x doesn't have a __str__() method.

烟柳画桥 2024-07-30 03:57:35

尝试这个:

str(i)

Try this:

str(i)
北城孤痞 2024-07-30 03:57:35

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

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

str(a)

相当于The same。

a.__str__()

如果您想将某些内容转换为 intfloat 等,则

There is no typecast and no type coercion in Python. You have to convert your variable in an explicit way.

To convert an object into a string you use the str() function. It works with any object that has a method called __str__() defined. In fact

str(a)

is equivalent to

a.__str__()

The same if you want to convert something to int, float, etc.

笑饮青盏花 2024-07-30 03:57:35

管理非整数输入:

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

To manage non-integer inputs:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0
只为守护你 2024-07-30 03:57:35
>>> 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
>>> 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
喵星人汪星人 2024-07-30 03:57:35

对于 Python 3.6,您可以使用 f-strings 新功能转换为string ,与 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'>

如需更详细的答案,您可以查看这篇文章:将 Python Int 转换为 String 以及将 Python String 转换为 Int

For Python 3.6, you can use the f-strings new feature to convert to string and it's faster compared to str() function. It is used like this:

age = 45
strAge = f'{age}'

Python provides the str() function for that reason.

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

For a more detailed answer, you can check this article: Converting Python Int to String and Python String to Int

你不是我要的菜∠ 2024-07-30 03:57:35

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

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

In Python => 3.6 you can use f formatting:

>>> int_value = 10
>>> f'{int_value}'
'10'
>>>
美胚控场 2024-07-30 03:57:35

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

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

The most decent way in my opinion is ``.

i = 32   -->    `i` == '32'
悲凉≈ 2024-07-30 03:57:35

您可以使用 %s.format

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

或者:

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

You can use %s or .format:

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

Or:

>>> '{}'.format(10)
'10'
>>>
只是在用心讲痛 2024-07-30 03:57:35

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

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

有关更多详细信息,您可以参考 Stack Overflow 问题显示带前导零的数字

For someone who wants to convert int to string in specific digits, the below method is recommended.

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

For more details, you can refer to Stack Overflow question Display number with leading zeros.

忆依然 2024-07-30 03:57:35

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

f'{10}' == '10'

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

事实上,它比 %x 字符串格式化和 .format() 更快!

With the introduction of f-strings in Python 3.6, this will also work:

f'{10}' == '10'

It is actually faster than calling str(), at the cost of readability.

In fact, it's faster than %x string formatting and .format()!

时光匆匆的小流年 2024-07-30 03:57:35

在 python 中,有多种方法可以将整数转换为字符串。
您可以使用 [ str(integer here) ] 函数、f 字符串 [ f'{integer here}']、.format() 函数 [ '{}'.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'>)


There are several ways to convert an integer to string in python.
You can use [ str(integer here) ] function, the f-string [ f'{integer here}'], the .format()function [ '{}'.format(integer here) and even the '%s'% keyword [ '%s'% integer here]. All this method can convert an integer to string.

See below example

#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'>)


谈场末日恋爱 2024-07-30 03:57:35

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

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]

Here is a simpler solution:

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

Output console

>>> 1

In the above program, int() is used to convert the string representation of an integer.

Note: A variable in the format of string can be converted into an integer only if the variable is completely composed of numbers.

In the same way, str() is used to convert an integer to string.

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

I used a list to print the output to highlight that variable (a) is a string.

Output console

>>> ["123567"]

But to understand the difference how a list stores a string and integer, view the below code first and then the output.

Code

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

Output console

>>> ["This is a string and next is an integer", 23]
回首观望 2024-07-30 03:57:35

您还可以调用 format()

format(42)                 # 42 --> '42'

如果您想添加千位分隔符:

num = 123456789
format(num, ",")           # '123,456,789'
f"{num:,}"
"{:,}".format(num)

或转换为浮点数的字符串表示形式

format(num, ",.2f")        # '123,456,789.00'
f"{num:,.2f}"
'{:,.2f}'.format(num)

对于“欧洲”分隔符:

format(num, "_.2f").replace('.', ',').replace('_', '.')   # '123.456.789,00'
f"{num:_.2f}".replace('.', ',').replace('_', '.')
"{:_.2f}".format(num).replace('.', ',').replace('_', '.')

You can also call format():

format(42)                 # 42 --> '42'

If you want to add a thousands separator:

num = 123456789
format(num, ",")           # '123,456,789'
f"{num:,}"
"{:,}".format(num)

or to convert to string representation of floats

format(num, ",.2f")        # '123,456,789.00'
f"{num:,.2f}"
'{:,.2f}'.format(num)

For a "European" separator:

format(num, "_.2f").replace('.', ',').replace('_', '.')   # '123.456.789,00'
f"{num:_.2f}".replace('.', ',').replace('_', '.')
"{:_.2f}".format(num).replace('.', ',').replace('_', '.')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文