1

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'
2
  • Why does it need to be an integer? Commented Apr 23, 2015 at 1:34
  • 1
    Integers do not have leading zeroes. I think what you're looking for is to format into a string with leading zeroes. Commented Apr 23, 2015 at 1:34

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.