[英]How to extract text from a string with Python using indexing and slicing
[英]Is there a way to retrieve specific string values using slicing and indexing?
我正在尝试从用户 email 地址中检索用户名和域。
例如:john.smith@apple.com
username = john.smith
domain = apple
我正在尝试从打印到控制台中删除“.com”。 请注意,其他 email 地址可能包含不同的结尾,例如“.ca”、“.org”等。
我也知道我可以使用 .partition() 方法,但是,我正在尝试通过切片和索引来完成此操作。
这是我到目前为止编写的一些代码:
mail = input("Enter email address: ")
username = email.find("@")
domain = email.find("@")
print("Username: " + email[:username])
print("Domain: " + email[domain+1:])
Output:
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”,从而只显示域中的主名称? 我是否在正确的轨道上找到“@”然后从那里切片?
您已经演示了应该用来解决这个问题的每一种技术。 您已经在加数处划分了完整的字符串; 现在对地址中的点执行相同的操作:
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)
像这样简单的事情应该可以解决问题。
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}')
output
username: john.smith domain:apple
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.