简体   繁体   English

Python:如何在固定字符串中的特定字符之前排除一组字符

[英]Python: How to exclude a group of characters before a specific character in a fixed string

Using a python script I want to exclude all characters at and before the '@' from the userlist*. 我想使用python脚本从用户列表中排除“ @”之前和之后的所有字符。 I only want to see the full domain names. 我只想查看完整的域名。 I have tried achieving this using regex, replace, substrings, custom functions etc... but nothing is generating the output I need. 我尝试使用正则表达式,替换,子字符串,自定义函数等实现此目的,但是没有任何东西可以生成我需要的输出。 I feel like I'm looking In the wrong direction and I must be missing something simple. 我觉得我朝着错误的方向前进,我肯定想念一些简单的事情。

* Userlist: *用户列表

user@domain.com
anotheruser@somedomain.org
superuser@domains.co.uk
foo@domain.com
email = 'user@domain.com'
_, domain = email.split('@')
print domain

>>> domain.com

For completeness, here is (a) solution using regular expressions: 为了完整起见,这是(a)使用正则表达式的解决方案:

>>> import re    
>>> re.search(r'(?<=@).*', 'me@example.com').group()
'example.com'

As an alternative to split() you can slice the index as follows 作为split()的替代方法,您可以按以下方式切片索引

email = 'user@domain.com'
domain = email[email.index['@']+1:]
print domain

>>> domain.com

This is a slightly safer version of @chishaku's answer; 这是@chishaku的答案的安全性更高的版本; it returns everything following the first occurrence of the target character or substring, and will not choke on 0 or multiple occurrences. 它会在目标字符或子字符串的第一次出现之后返回所有内容,并且不会因0次或多次出现而阻塞。

def after_first(ch, s):
    return s.split(ch, 1)[-1]

for user in userlist:
    print after_first("@", user)

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

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