使用的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
,如上所述的。
>>> 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: [email protected]>, <User: awe_so/me>]'
>>> r.findall(strs)
['[email protected]', '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']]
請參閱我更新的問題。 – pynovice
@ user2032220我已經更新了我的答案。 –
'lstrip'是個不錯的主意。引用文檔:「字符參數不是一個前綴;相反,它的值的所有組合都被剝離」。它適用於這組值,但是如果其中一個值是'[<用戶:尊重>]',它會給你'pect>]'。 – Matthias