Joe
Joe

Reputation: 13

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'

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'

Upvotes: 1

Views: 1728

Answers (3)

monkut
monkut

Reputation: 43870

Using string-formatting via the .format() method is good for this.

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.

Therefore, using "{:04}".format(0) will result in the string, "0000".

Upvotes: 0

Deacon
Deacon

Reputation: 3813

If I understand you correctly, you're going to be using the int in a string, correct? 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). You convert it to that format when you create format_string.

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180512

You cannot have leading zeros at all in python3 and in python 2 they signify octal numbers. 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:

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.

Upvotes: 4

Related Questions