-1

my teacher asked me to write a program which will read an account number from a keyboard and then display it in the format as below:

input: 12103400001212905611117806 output: 12 1034 0000 1212 9056 1111 7806

I tried to do it, but I am new to Python and I don't know how to split this input after "12" and then every other four. Can someone give me some advice how to do it? I've started with for loop which look like this:

acc_number = input("Enter your account number: ")
for i in acc_number:
    print(i, end = "")

I would be really grateful for help!

  • 1
    Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – Chase Oct 20 '20 at 15:06
  • You can slice the first two numbers, store it in a variable and then loop the rest, slicing every 4 characters and adding a space in the beginning of each one sliced item. In the end, return the variable with all the sliced items. – Eduardo Matsuoka Oct 20 '20 at 15:10

3 Answers3

1

This is a bit of a messy solution, but it works, and does it in one line, without being hardcoded to the format like some other solutions:

acc_number = input("Enter your account number: ")
print(acc_number[:2] + ' ' + ' '.join([acc_number[i*4 + 2:(i+1)*4 + 2] for i in range(int(len(num)/4))]))

Reference for the techniques used:

This question is probably better suited for a site place r/learnpython, which is more welcoming to beginners. Good luck learning Python!

sebtheiler
  • 2,159
  • 3
  • 16
  • 29
1

You could do this by slicing the string:

i = input("Enter your account number: ")
print(f'{i[:2]} {i[2:6]} {i[6:10]} {i[10:14]} {i[14:18]} {i[18:22]} {i[22:26]}') 

This of course only works if the input is in the same format every time.

0

This works for me.

  1. Define a blank array and blank string (aptly named).
  2. User enters their account number and each character is added to the array.
  3. Add the spaces into the array where they are needed.
  4. Each character from the array is then concatenated together to make a string.
  5. Print the string on screen.

array = []
string = ""

acc_number = input("Enter your account number: ")

for i in acc_number:
    array.append(i)

array.insert(2," ")
array.insert(7," ")
array.insert(12," ")
array.insert(17," ")
array.insert(22," ")
array.insert(27," ")

for i in array:
    string += i

print(string)