簡體   English   中英

在 Python 中將整數轉換為字符串

[英]Converting integer to string in Python

嘗試my_int.str()會出現錯誤,指出int沒有任何名為str的屬性。

>>> str(10)
'10'

>>> int('10')
10

文檔鏈接:

轉換為字符串是使用內置的str()函數完成的,該函數基本上調用其參數的__str__()方法。

嘗試這個:

str(i)

Python 中沒有類型轉換和類型強制。 您必須以顯式方式轉換變量。

要將對象轉換為字符串,請使用str()函數。 它適用於任何定義了名為__str__()的方法的對象。 實際上

str(a)

相當於

a.__str__()

如果您想將某些內容轉換為intfloat等,則相同。

管理非整數輸入:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0
>>> 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

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

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

對於 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

我認為最體面的方式是``。

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

您可以使用%s.format

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

或者:

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

對於想要將 int 轉換為特定數字的字符串的人,建議使用以下方法。

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

有關更多詳細信息,您可以參考 Stack Overflow 問題Display number withleading zeros

隨着 Python 3.6 中f-strings的引入,這也將起作用:

f'{10}' == '10'

它實際上比調用str()更快,但以可讀性為代價。

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

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


這是一個更簡單的解決方案:

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]

如果你需要一元數字系統,你可以像這樣轉換一個整數:

>> n = 6
>> '1' * n
'111111'

如果你需要負整數的支持,你可以這樣寫:

>> n = -6
>> '1' * n if n >= 0 else '-' + '1' * (-n)
'-111111'

零是特殊情況,在這種情況下采用空字符串,這是正確的。

>> n = 0
>> '1' * n if n >= 0 else '-' + '1' * (-n)
''

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM