![](/img/trans.png)
[英]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.