Home > Net >  How to replace email pattern with name in Python?
How to replace email pattern with name in Python?

Time:06-08

I have a list of varying email patterns that I want to replace with actual names. The pattern has to include at least the first or last name, and it can be a subset of the name (indicated by the length of characters between the curly brackets). For example, let's say I want to find the email of John Doe with these email patterns below. It should look like the following:

I have no idea how to do this in Python. I have little experience in regex and would love some tips on how to get started on this. Thanks!

CodePudding user response:

def email(first_last,domain):
    first, last = first_last.lower().split(' ')
    f = first[0]
    print(f'{first}{last}@{domain}')  # [email protected]
    print(f'{f}{last}@{domain}')      # [email protected]
    print(f'{last}123@{domain}')      # [email protected]
    print(f'{last}-{f}@{domain}')     # [email protected]

Now test it:

email('John Doe','domain.com')

[email protected]
[email protected]
[email protected]
[email protected]

CodePudding user response:

{first}{last}@domain.com becomes [email protected]
{f}{last}@domain.com becomes [email protected]
{last}[email protected] becomes [email protected]
{last}-{f}@domain.com becomes [email protected]

Things of left seems to be valid strings for usage with .format method of str. If this does hold true for all your records, you might use said method as follows

print("{first}{last}@domain.com".format(first="John",last="Doe"))
print("{f}{last}@domain.com".format(f="j",last="doe"))
print("{last}[email protected]".format(last="doe"))
print("{last}-{f}@domain.com".format(f="j",last="doe"))

output

[email protected]
[email protected]
[email protected]
[email protected]

be warned that your markers do not discern case (e.g. last in 1st is Doe whilst in 4th is doe)

  • Related