Python 3:在特定条件下分割字符串

时间:2018-06-22 15:22:25

标签: python string python-3.x split delimiter

在将字符串拆分成Python 3的特定部分时,我遇到了困难。 该字符串基本上是一个以冒号(:)作为分隔符的列表。

仅当冒号(:)带有反斜杠(\)前缀时, 不算作分隔符,而是列表项的一部分。

示例:

String --> I:would:like:to:find\:out:how:this\:works

Converted List --> ['I', 'would', 'like', 'to', 'find\:out', 'how', 'this\:works']

有人知道这怎么工作吗?

@Bertrand,我试图为您提供一些代码,并且能够找出解决方法,但这可能不是最漂亮的解决方案

text = "I:would:like:to:find\:out:how:this\:works"

values = text.split(":")
new = []
concat = False
temp = None

for element in values:

    # when one element ends with \\

    if element.endswith("\\"):
        temp = element
        concat = True

    # when the following element ends with  \\ 
    # concatenate both before appending them to new list

    elif element.endswith("\\") and temp is not None:
        temp = temp + ":" + element
        concat = True

   # when the following element does not end with \\
   # append and set concat to False and temp to None

    elif concat is True:
        new.append(temp + ":" + element)
        concat = False
        temp = None

   # Append element to new list

    else:
        new.append(element)

print(new)

输出:

['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']

3 个答案:

答案 0 :(得分:3)

您应该使用re.split并在后面进行负向查找来检查反斜杠字符。

import re
pattern = r'(?<!\\):'
s = 'I:would:like:to:find\:out:how:this\:works'
print(re.split(pattern, s))

输出:

['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']

答案 1 :(得分:2)

您可以将“:\”替换为某些内容(只需确保此内容在其他位置的字符串中不存在...您可以使用长期名称或其他内容),然后用“ :“,然后重新装回。

str1 = 'I:would:like:to:find\:out:how:this\:works'

说明:

str1.replace("\:","$")
Out: 'I:would:like:to:find$out:how:this$works'

将“:”替换为“ $”(或其他符号):

str1.replace("\:","$").split(":")
Out: ['I', 'would', 'like', 'to', 'find$out', 'how', 'this$works']

现在用“:”分隔

[x.replace("$","\:") for x in str1.replace("\:","$").split(":")]
Out: ['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']

并为每个元素用“:”替换“ $”:

switch (action.type) {
    case UPDATE_PROGRESS: {
      let formState = state.get('formState');
      formState = formState.set('progress', action.payload)
      console.log(formState);
      return state
        .set('formState', formState);
    }

答案 2 :(得分:1)

使用re.split

例如:

import re
s = "I:would:like:to:find\:out:how:this\:works"
print( re.split(r"(?<=\w):", s) )

输出:

['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']