Home > Mobile >  Need to find last @ in the string using a loop preferably
Need to find last @ in the string using a loop preferably

Time:08-25

I'm trying to replace old domain from email if matches, and if i want to include all pre @ then how to iterate till last @ and only from there remove old domain. preferred output - demo@@@@.google.com

def replace_email(email,old_domain,new_domain):
    if "@" old_domain in email:
        index = email.index("@")
        new_email = email[:index]  "@" new_domain
        return new_email
    return email
print(replace_email('demo@@@@@drungston.com','drungston.com','google.com'))
print(replace_email('test@@@yahoo.com','yahoo.com','yahoo.com'))

CodePudding user response:

There is no need to use a loop to find the last occurrence of a character in a string as you can simply use rindex

def replace_email(email, old_domain, new_domain):
    if '@' in email:
        email = email[:email.rindex('@')]   email[email.rindex('@'):].replace(old_domain, new_domain) 
    return email

This will preserve the number of @ in your output (although, as noted above, your explanation doesn't match your preferred output).

print(replace_email('demo@@@@@drungston.com','drungston.com','google.com'))
demo@@@@@google.com

If you wanted to eliminate the excess @s, it would be as simple as changing rindex to index in the first half of the function.

def replace_email(email, old_domain, new_domain):
    if '@' in email:
        email = email[:email.index('@')]   email[email.rindex('@'):].replace(old_domain, new_domain) 
    return email
  • Related