Python-将字符串转换为整数,同时保持前导零
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
>>>
您不需要将变量存储为格式为 001
的 int
(无论如何您都做不到)。创建 format_string
.
时将其转换为该格式
通过 .format()
方法使用 string-formatting 对此有好处。
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"
.
我正在尝试将字符串(例如 '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
>>>
您不需要将变量存储为格式为 001
的 int
(无论如何您都做不到)。创建 format_string
.
通过 .format()
方法使用 string-formatting 对此有好处。
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"
.