简体   繁体   English

有没有办法使用切片和索引来检索特定的字符串值?

[英]Is there a way to retrieve specific string values using slicing and indexing?

I am trying to retrieve the username and domain from a user email address.我正在尝试从用户 email 地址中检索用户名和域。

For example: john.smith@apple.com例如:john.smith@apple.com

username = john.smith    
domain = apple

I am trying to remove the ".com" from being printed to the console.我正在尝试从打印到控制台中删除“.com”。 Note, other email addresses could account for different endings such as ".ca", ".org", etc.请注意,其他 email 地址可能包含不同的结尾,例如“.ca”、“.org”等。

I also know I can use the.partition() method, however, I am trying to accomplish this with slicing and indexing.我也知道我可以使用 .partition() 方法,但是,我正在尝试通过切片和索引来完成此操作。

Here is some code I have written so far:这是我到目前为止编写的一些代码:

mail = input("Enter email address: ")

username = email.find("@")
domain = email.find("@")

print("Username: " + email[:username])

print("Domain: " + email[domain+1:])

Output: Output:

Enter email address: john.smith@apple.com
Username: john.smith
Domain: apple.com

Goal:目标:

Enter email address: john.smith@apple.com
Username: john.smith
Domain: apple

Is there a way (only through indexing and slicing) that I can account for any amount of chars a user inputs to console, and remove the ".com" or ".ca", thus, only displaying the main name in the domain?有没有办法(仅通过索引和切片)我可以解释用户输入到控制台的任意数量的字符,并删除“.com”或“.ca”,从而只显示域中的主名称? Am I on the right track with finding the "@" and then slicing it from there?我是否在正确的轨道上找到“@”然后从那里切片?

You already demonstrated every technique you should use to solve this.您已经演示了应该用来解决这个问题的每一种技术。 You already divided the full string at the addend;您已经在加数处划分了完整的字符串; now do the same for the dot in the address:现在对地址中的点执行相同的操作:

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)

Something as simple as this should do the trick.像这样简单的事情应该可以解决问题。

email = "john.smith@apple.com".split('@')
username,domain= email[0],email[1].split('.')[0]
print(f'username: {username}\ndomain:{domain}')

broken down坏了

  • simple break it down to ["john.smith","apple.com"]简单地将其分解为 ["john.smith","apple.com"]
  • username is first element in list用户名是列表中的第一个元素
  • domain will take the second element in the list domain 将采用列表中的第二个元素
  • split that element and take "apple" (first index)拆分该元素并取“苹果”(第一个索引)
     email = "john.smith@apple.com".split('@') username = email[0] domain = email[1].split('.')[0] print(f'username: {username}\ndomain:{domain}')

    output output

     username: john.smith domain:apple
  • 声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM