-2

I am learning to do some string manipulation python as you can see below trying to insert a character, but after some run it fails. Can you explain why ?

phone_num = str("+1-202-555--+0143+")


wrng = ['+','-']

for a in phone_num:    
    if a in wrng:
        b = phone_num.find(a)
        c = phone_num.rfind(a)
        if type(b)!= int or float:
            phone_num = phone_num[:b]+'0'+phone_num[b:]
            print(phone_num)
        elif type(c) != int or float:
            phone_num = phone_num[:c]+'0'+phone_num[c:]
        else:
            print("Wrong")

also trying to add the end but it fails.

0+1-202-555--+0143+
0+10-202-555--+0143+
0+100-202-555--+0143+
0+1000-202-555--+0143+
0+10000-202-555--+0143+
00+10000-202-555--+0143+
000+10000-202-555--+0143+

expecting was 0+1-202-555-0-0+0143+0

1 Answers1

0

I'll explain what your code does and hope it'll help a bit with further steps.

It executes seven times since you have seven symbols, therefore you have 7 lines of output.

The first part of the first condition type(a)!= int always evaluates for true, since you only get there if a is either + or -. The float part of the boolean check will always evaluate to true, so you can delete it, there also will never be floats in a single character.

Whenever it is +, b will be the index of the leftmost + and the function will add a 0 in front of it. In the case it's a -, b will be the index of the leftmost - and add a 0 in front of that.

Lukas Schmid
  • 1,895
  • 1
  • 6
  • 18