使用sts.lstrip
和的组合str.rstrip
:
演示:
>>> strs = '[<User: mr--adhikari>]'
>>> strs = strs.lstrip('[<User: ')
>>> strs
'mr--adhikari>]'
>>> strs = strs.rstrip('>]')
>>> strs
'mr--adhikari'
代码:
>>> hello = [['<User: mr--adhikari>'], ['<User: mr--adhikari>'], ['<User: mr--adhikari>', '<User: awesome>']]
>>> [ [y.lstrip('<User: ').rstrip('>') for y in x] for x in hello ]
[['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari', 'awesome']]
更新:
>>> shared_username = ['[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>, <User: awesome>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]']
>>> [[y.lstrip('[<User: ').rstrip('>]') for y in x.split(', ')] for x in shared_username]
[['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari', 'awesome'], ['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari']]
演示:
strs = '[<User: mr--adhikari>, <User: awesome>]'
首先拆分字符串', '
以获取字符串列表,现在循环此列表并应用str.lstrip
,str.rstrip
如上所述。
>>> strs.split(', ')
['[<User: mr--adhikari>', '<User: awesome>]']
更新:
使用regex
:
演示:
>>> import re
>>> r = re.compile(r'User:\s([A-Za-z\-._/@]+)')
>>> strs = '[<User: sachitad>, <User: awesome>]'
>>> r.findall(strs)
['sachitad', 'awesome']
>>> strs1 = '[<User: mr--adhikari>, <User: awesome>]'
>>> r.findall(strs1)
['mr--adhikari', 'awesome']
>>> strs2 = '[<User: respect>]'
>>> r.findall(strs2)
['respect']
>>> strs = '[<User: sa@chi.tad>, <User: awe_so/me>]'
>>> r.findall(strs)
['sa@chi.tad', 'awe_so/me']
代码:
>>> shared_username = ['[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>, <User: awesome>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]']
>>> [r.findall(item) for item in shared_username]
[['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari', 'awesome'], ['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari'], ['mr--adhikari']]