[英]Python-Turning a string into and integer while keeping leading zeros
我正在嘗試將字符串(例如“ AB0001”)轉換為顯示為“ 001”的整數
我在嘗試:
x='AB0001'
z=int(x[2:len(x)])
雖然我的輸出是:
1
我需要將其用作整數:
format_string=r'/home/me/Desktop/File/AB'+r'%05s'+r'.txt' % z
感謝您的寶貴時間,請讓我知道如何獲得以下結果:
format_string=r'/home/me/Desktop/File/AB0001.txt'
在python3中,根本不能有前導零,而在python 2中,它們表示octal
數。 如果要將其傳遞給字符串,只需將其保留為字符串即可。
如果要用0填充,可以zfill:
print(x[2:].zfill(5))
我看不到為什么您似乎想要與原始字符串完全一樣的輸出時卻完全想不到。
format_string=r'/home/me/Desktop/File/{}.txt'.format(x)
會給您您想要的。
如果我對您的理解正確,那么您將在字符串中使用int
,對嗎? 既然是這種情況,您應該完全按照自己的方式做:
>>> x = 1
>>> format_string = r'/home/me/Desktop/File/AB%04d.txt' % x
>>> print(format_string)
/home/me/Desktop/File/AB0001.txt
>>>
您無需將變量存儲為int
格式為001
(無論如何都不能這樣做)。 創建format_string
時,可以將其轉換為該格式。
通過.format()
方法使用字符串格式對此很有用。
x='AB0001'
resulting_int_value =int(x[2:]) # omitting the last index of a slice operation will automatically assign the end of the string as the index
resulting_string = r'/home/me/Desktop/File/AB{:04}.txt'.format(resulting_int_value)
結果是:
'/home/me/Desktop/File/AB0001.txt'
這里, {:04}
是格式說明符,它告訴字符串通過填充最多4個前導零來格式化給定值。
因此,使用"{:04}".format(0)
將導致字符串"0000"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.