When the user enters an email address, and the program reads the email and display it according to its criteria (e.g yeo.myy@edu.co
), like criteria:
username
isyeo.myy
domain
isedu.co
I know its something to do with the "@"
.
this is the code
JavaScript
x
30
30
1
class Email:
2
def __int__(self,emailAddr):
3
self.emailAddr = emailAddr
4
5
6
def domain(self):
7
index = 0
8
for i in range(len(emailAddr)):
9
if emailAddr[i] == "@":
10
index = i
11
return self.emailAddr[index+1:]
12
13
def username(self):
14
index = 0
15
for i in range(len(emailAddr)):
16
if emailAddr[i] == "@" :
17
index = i
18
return self.emailAddr[:index]
19
20
def main():
21
22
emailAddr = raw_input("Enter your email>>")
23
24
user = Email(emailAddr)
25
26
print "Username = ", user.username()
27
print "Domain = ", user.domain()
28
29
main()
30
this is the error I got:
JavaScript
1
7
1
Traceback (most recent call last):
2
File "C:/Users/Owner/Desktop/sdsd", line 29, in <module>
3
main()
4
File "C:/Users/Owner/Desktop/sdsd", line 24, in main
5
user = Email(emailAddr)
6
TypeError: this constructor takes no arguments
7
Advertisement
Answer
JavaScript
1
2
1
def __int__(self,emailAddr):
2
Did you mean __init__
?
JavaScript
1
2
1
def __init__(self,emailAddr):
2
You’re also missing a couple self
s in your methods, and your return
s are improperly indented.
JavaScript
1
14
14
1
def domain(self):
2
index = 0
3
for i in range(len(self.emailAddr)):
4
if self.emailAddr[i] == "@":
5
index = i
6
return self.emailAddr[index+1:]
7
8
def username(self):
9
index = 0
10
for i in range(len(self.emailAddr)):
11
if self.emailAddr[i] == "@" :
12
index = i
13
return self.emailAddr[:index]
14
Result:
JavaScript
1
3
1
Username = yeo.myy
2
Domain = edu.co
3
Incidentally, I recommend partition
and rpartition
for splitting a string into two pieces on a given separator. Sure beats keeping track of indices manually.
JavaScript
1
5
1
def domain(self):
2
return self.emailAddr.rpartition("@")[2]
3
def username(self):
4
return self.emailAddr.rpartition("@")[0]
5