简体   繁体   English

Python-将字符串转换为和整数,同时保持前导零

[英]Python-Turning a string into and integer while keeping leading zeros

I am trying to convert a string, such as 'AB0001', to an integer that appears as '001' 我正在尝试将字符串(例如“ AB0001”)转换为显示为“ 001”的整数

I am trying: 我在尝试:

x='AB0001'
z=int(x[2:len(x)])

though my output is: 虽然我的输出是:

1

I need this to be an integer to be used in: 我需要将其用作整数:

format_string=r'/home/me/Desktop/File/AB'+r'%05s'+r'.txt' % z

Thank you for your time and please let me know how to acquire the following outcome: 感谢您的宝贵时间,请让我知道如何获得以下结果:

format_string=r'/home/me/Desktop/File/AB0001.txt'

You cannot have leading zeros at all in python3 and in python 2 they signify octal numbers. 在python3中,根本不能有前导零,而在python 2中,它们表示octal数。 If you are going to pass it into a string just keep it as a string. 如果要将其传递给字符串,只需将其保留为字符串即可。

If you want to pad with 0's you can zfill: 如果要用0填充,可以zfill:

print(x[2:].zfill(5))

I don't see why you slice at all thought when you seem to want the exact same output as the original string. 我看不到为什么您似乎想要与原始字符串完全一样的输出时却完全想不到。

 format_string=r'/home/me/Desktop/File/{}.txt'.format(x)

will give you exactly what you want. 会给您您想要的。

If I understand you correctly, you're going to be using the int in a string, correct? 如果我对您的理解正确,那么您将在字符串中使用int ,对吗? Since this is the case, you should do exactly what you're doing: 既然是这种情况,您应该完全按照自己的方式做:

>>> x = 1
>>> format_string = r'/home/me/Desktop/File/AB%04d.txt' % x
>>> print(format_string)
/home/me/Desktop/File/AB0001.txt
>>>

You don't need to store the variable as an int with the format 001 (which you can't do anyway). 您无需将变量存储为int格式为001 (无论如何都不能这样做)。 You convert it to that format when you create format_string . 创建format_string时,可以将其转换为该格式。

Using string-formatting via the .format() method is good for this. 通过.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)

Results in: 结果是:

'/home/me/Desktop/File/AB0001.txt'

Here, {:04} is a format specifier telling string to format the given value by filling with up to 4 leading zeros. 这里, {:04}是格式说明符,它告诉字符串通过填充最多4个前导零来格式化给定值。

Therefore, using "{:04}".format(0) will result in the string, "0000" . 因此,使用"{:04}".format(0)将导致字符串"0000"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM