我正在尝试从用户电子邮件地址检索用户名和域。
例如:john.smith@apple.com
username = john.smith
domain = apple
我正在尝试将“.com”从打印到控制台中删除。请注意,其他电子邮件地址可能会有不同的结尾,例如 ".ca"、".org" 等。
我也知道我可以使用 .partition() 方法,但是,我正在尝试通过切片和索引来实现这一点。
这是我目前编写的一些代码:
mail = input("Enter email address: ")
username = email.find("@")
domain = email.find("@")
print("Username: " + email[:username])
print("Domain: " + email[domain+1:])
输出:
Enter email address: john.smith@apple.com
Username: john.smith
Domain: apple.com
目标:
Enter email address: john.smith@apple.com
Username: john.smith
Domain: apple
有没有办法(仅通过索引和切片),我可以考虑用户输入到控制台的任意数量的字符,并删除“.com”或“.ca”,从而,只显示域中的主要名称?我是否在正确的轨道上找到“@”然后从那里切片?
答案 0 :(得分:2)
您已经演示了解决此问题应该使用的所有技术。您已经在加数处分割了完整的字符串;现在对地址中的点执行相同的操作:
domain = email[domain+1:] # "apple.com"
dot = domain.find(`.`) # Get position of the dot ...
company = domain[:dot] # and take everything up to that position.
print(company)
答案 1 :(得分:1)
像这样简单的事情应该可以解决问题。
email = "john.smith@apple.com".split('@')
username,domain= email[0],email[1].split('.')[0]
print(f'username: {username}\ndomain:{domain}')
崩溃了
email = "john.smith@apple.com".split('@')
username = email[0]
domain = email[1].split('.')[0]
print(f'username: {username}\ndomain:{domain}')
输出
username: john.smith
domain:apple