For loop concept

Question:

def domain(email, old_domain, new_domain):
    if "@" + old_domain in email:
        index = email.index("@" + old_domain)
        new_email = email[:index] + "@" + new_domain
        return new_email
    return email
    email = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']

old_domain = "yahoo.com"
new_domain = "gmail.com"
for i in email:
    print(i.domain(email, old_domain, new_domain))

The error is:

Traceback (most recent call last):
  File "/private/tmp/p4", line 11, in <module>
    print(i.domain(email, old_domain, new_domain))
AttributeError: 'str' object has no attribute 'domain'

in Above coding i tried to loop the each string with the function that i define but it keep on comming error. what mistake have i done? please kindly anyone correct it.

Asked By: Sandeep PC

||

Answers:

The code you’ve provided has a few mistakes that are causing errors:

for i in email: print(i.domain(email, old_domain, new_domain))
Here you are trying to access the function domain() as a method of the string i, however domain() is a separate function and it is not a method of the string.
So instead of i.domain(email, old_domain, new_domain) use domain(i, old_domain, new_domain)

Also email is already defined as a list, you don’t need to pass it again as an argument in the domain() function

On top of that, you don’t need a list of email to iterate through, you can directly pass it one by one, So instead of passing the whole list of emails, you need to pass one email at a time

Here’s the corrected version of the code:

def domain(email, old_domain, new_domain):
if "@" + old_domain in email:
    index = email.index("@" + old_domain)
    new_email = email[:index] + "@" + new_domain
    return new_email
return email

email = [‘[email protected]’, ‘[email protected]’, ‘[email protected]’, ‘[email protected]’]
old_domain = "yahoo.com"
new_domain = "gmail.com"
for i in email:
print(domain(i, old_domain, new_domain))

Answered By: Roger Rhodes

Your last two lines should read:

for i in email:
    print(domain(i, old_domain, new_domain))

As commented above, email is a list of strings and you need to pass each individual string. The end result should be:

def domain(email, old_domain, new_domain):
    if "@" + old_domain in email:
        index = email.index("@" + old_domain)
        new_email = email[:index] + "@" + new_domain
        return new_email
    return email
email = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']
old_domain = "yahoo.com"
new_domain = "gmail.com"
for i in email:
    print(domain(i, old_domain, new_domain))

which gives the output:

[email protected]
[email protected]
[email protected]
[email protected]
Answered By: Thickycat
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.