【问题标题】:How to add parenthesis around a substring in a string?如何在字符串中的子字符串周围添加括号?
【发布时间】:2018-10-20 01:13:59
【问题描述】:

我需要在这样的字符串中的子字符串(包含 OR 布尔运算符)周围添加括号:

message = "a and b amount OR c and d amount OR x and y amount"

我需要到达这个:

message = "(a and b amount) OR (c and d amount) OR (x and y amount)"

我试过这段代码:

import shlex
message = "a and b amount OR c and d amount OR x and y amount"
target_list = []

#PROCESS THE MESSAGE.
target_list.append(message[0:message.index("OR")])
args = shlex.split(message)
attribute = ['OR', 'and']
var_type = ['str', 'desc']

for attr, var in zip(attribute, var_type):
    for word in args:
        if word == attr and var == 'str': target_list.append(word+' "')
        else: target_list.append(word)
print(target_list)

但它似乎不起作用,代码只是返回原始消息的多个副本并且没有在句尾添加括号。我该怎么办?

【问题讨论】:

    标签: python string shlex


    【解决方案1】:

    如果您的字符串始终是由 OR 分隔的术语列表,您可以拆分并加入:

    >>> " OR ".join("({})".format(s.strip()) for s in message.split("OR"))
    '(a and b amount) OR (c and d amount) OR (x and y amount)'
    

    【讨论】:

      【解决方案2】:

      一些字符串操作函数应该可以在不涉及外部库的情况下解决问题

      " OR ".join(map(lambda x: "({})".format(x), message.split(" OR ")))
      

      或者,如果你想要一个更易读的版本

      sentences = message.split(" OR ")
      # apply parenthesis to every sentence
      sentences_with_parenthesis = list(map(lambda x: "({})".format(x), sentences))
      result = " OR ".join(sentences_with_parenthesis)
      

      【讨论】:

        【解决方案3】:

        您可能只想将所有子句分解成一个列表,然后 用括号加入他们。像这样的东西,虽然它 即使没有 OR 子句也添加括号:

        original = "a and b OR c and d OR e and f"
        clauses = original.split(" OR ")
        # ['a and b', 'c and d', 'e and f']
        fixed = "(" + ") OR (".join(clauses) + ")"
        # '(a and b) OR (c and d) OR (e and f)'
        

        【讨论】:

          猜你喜欢
          • 2018-11-17
          • 2022-06-23
          • 1970-01-01
          • 2013-03-11
          • 1970-01-01
          • 2013-10-08
          • 1970-01-01
          • 2021-08-22
          • 2013-02-24
          相关资源
          最近更新 更多