'How to format a user input into a different out put?Python
How can from an input (10 number): XXXXXXXXXX
convert into : X.XX.XX.XX.XXXX
So far this is my code:
creat_number_account = input("Account Number:")
def c_n_account(creat_number_account):
if len(creat_number_account) <10:
print("This account require 10 numbers")
elif n_list[10] == "0":
print("The last number can't be: '0'")
else:
list =[]
for n in creat_number_account:
list+= n
print(f'{list [0]}.{list[1][2]}.'
f'{list[3][4]}.{list[5][6]}.{list[7][8][9][-1]}')
print(c_n_account(creat_number_account))
OUTPUT:
print(f'{list [0]}.{list[1][2]}.'
IndexError: string index out of range
Solution 1:[1]
Adding to answer by @Sefan, keep prompting the user until the correct format is recevied:
n = input("Account Number:")
def c_n_account(n):
while True:
if len(n) < 10 or len(n) > 10:
print("This account requires 10 numbers only")
n = input("Account Number:")
continue
elif n[9] == "0":
print("The last number can't be: '0'")
n = input("Account Number:")
continue
else:
act = f"{n[0]}.{n[1:3]}.{n[3:5]}.{n[5:7]}.{n[7:]}{n[-1]}"
return act
break
print(c_n_account(n))
Solution 2:[2]
You can use creat_number_account[1:3] if you want to print more than 1 character from the input string.
Something like this should work for you:
creat_number_account = input("Account Number:")
def c_n_account(creat_number_account):
if len(creat_number_account) <10:
print("This account require 10 numbers")
elif creat_number_account[10] == "0":
print("The last number can't be: '0'")
else:
print(f'{creat_number_account[0]}.{creat_number_account[1:3]}.{creat_number_account[3:5]}.{creat_number_account[5:7]}.{creat_number_account[7:]}')
You should add a check if the input is bigger than 10 characters.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sefan |
