有没有办法使用切片和索引来检索特定的字符串值?
Is there a way to retrieve specific string values using slicing and indexing?
我正在尝试从用户电子邮件地址中检索用户名和域。
例如: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”,因此,只显示域中的主要名称?我是否在正确的轨道上找到“@”然后从那里切片?
像这样简单的东西应该可以解决问题。
email = "john.smith@apple.com".split('@')
username,domain= email[0],email[1].split('.')[0]
print(f'username: {username}\ndomain:{domain}')
崩溃了
简单分解为 ["john.smith","apple.com"]
用户名是列表中的第一个元素
域将取列表中的第二个元素
拆分该元素并取 "apple"(第一个索引)
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
您已经演示了解决此问题应使用的所有技术。您已经在加数处划分了完整的字符串;现在对地址中的点执行相同的操作:
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)
我正在尝试从用户电子邮件地址中检索用户名和域。
例如: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”,因此,只显示域中的主要名称?我是否在正确的轨道上找到“@”然后从那里切片?
像这样简单的东西应该可以解决问题。
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
您已经演示了解决此问题应使用的所有技术。您已经在加数处划分了完整的字符串;现在对地址中的点执行相同的操作:
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)