拆分可能存在或不存在的字符串列表

时间:2016-12-27 05:12:26

标签: python

如何使用变量中可能存在或不存在的字符串列表进行拆分?

root

但这不起作用......

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

因此,拆分一次只能使用一个字符串(docs here)。因此,对于您的情况,如果您有可能拆分字符串的列表,我们必须遍历每个字符串并尝试拆分:

list_of_passwords = ['Password is', 'Pwd:', 'password:']
my_string = 'This is my string that contains Pwd: 89237'
collected_password = None
for x in list_of_passwords:
    pieces = my_string.split(x, 1) # split the string at most 1 time(s)
    if len(pieces) == 2: # we know we had a split if there are two pieces
        collected_password = pieces[-1] # grab the last part of the split

print collected_password.strip()

您也可以使用re(docs here):

对正则表达式执行此操作
import re

list_of_passwords = ['Password is', 'Pwd:', 'password:']
my_string = 'This is my string that contains Pwd: 89237'
# format the list of passwords separated by the OR
splitter = re.compile('(%s)' % ('|'.join(list_of_passwords)))

pieces = splitter.split(my_string)
collected_password = pieces[-1].strip() # grab the last part of the split

答案 1 :(得分:1)

您可以使用正则表达式split

list_of_passwords = ['Password is', 'Pwd:', 'password:']
my_string = 'This is my string that contains Pwd: 89237'

import re

collected_password = re.split(' |'.join(list_of_passwords), my_string)

print(collected_password)

输出:

['This is my string that contains ', '89237']