user1248367
user1248367

Reputation: 27

Replacing in Python

I need to complete a basic task on Python that requires me to convert a standard phone number into an international one.

So for example, if the users phone number was 0123456789, the program should display, Your international phone number is +44123456789.

I don't know how to replace the 0 with a 44. I don't know many techniques on Python so advice on how to is welcomed, thanks.

EDIT:

    #Python Number Conversion
def GetInternational(PhoneNumber):
    if num.startswith('0'):
        num = num.replace('0','+44',1)
        return GetInternational

PhoneNumber = input("Enter your phone number: ")
print('Your international number is',GetInternational,'')

I'm missing something obvious but not sure what...

Upvotes: 0

Views: 367

Answers (2)

Akavall
Akavall

Reputation: 86188

Another way to do it would be:

num.replace('0','+44',1) #Only one, the leftmost zero is replaced

Therefore if the number starts with zero we replace only that one,

num = "0123456789"

if num.startswith('0'):
    num = num.replace('0','+44',1)

Upvotes: 4

orlp
orlp

Reputation: 117691

Well the simplest way to do it is strip off the first character (the 0) and then concatenate it with +"44":

num = "0123456789"

if num.startswith("0"):
    num = "+44" + num[1:]

For clarity I added a startswith check to make sure the substitution only happens if the number starts with a zero.

Upvotes: 3

Related Questions