【问题标题】:Is there a way to retrieve specific string values using slicing and indexing?有没有办法使用切片和索引来检索特定的字符串值?
【发布时间】:2021-08-11 02:58:30
【问题描述】:

我正在尝试从用户电子邮件地址中检索用户名和域。

例如: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”,因此,只显示域中的主要名称?我是否在正确的轨道上找到“@”然后从那里切片?

【问题讨论】:

  • final = email.rfind("."),然后是print("Domain: " + email[domain+1:final])。但是,这通常是 regular expressions 的工作。
  • 你可以使用 .split("@") 然后 split('.') 吗?
  • @Malo 这个问题只能通过切片和使用 .find() 来解决。

标签: python python-3.x string indexing slice


【解决方案1】:

像这样简单的事情应该可以解决问题。

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

分解

  • 简单地将其分解为 ["john.smith","apple.com"]
  • 用户名是列表中的第一个元素
  • domain 将采用列表中的第二个元素
  • 拆分该元素并取“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
    
  • 【讨论】:

    • 我的目标是不打印“com”或“org”,而是打印此示例的“apple”部分。如果不使用 .split() 或 .partition() 我将如何做到这一点?
    • domain = email[1].split('.')[0] 将在此处返回“apple”
    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 2018-06-11
      相关资源
      最近更新 更多