【问题标题】:Python check if string contains words from specific list of stringsPython检查字符串是否包含特定字符串列表中的单词
【发布时间】:2021-06-24 07:55:50
【问题描述】:

我有一个字符串列表。

constants = ["{{first_name}}", "{{last_name}}", "{{order_num}}", {{order_date}}"]

order_string = " Hello, {{first_name}} {{last_name}}, Thanks for purchasing. You order number is {{order_num}} "

我有两个输入,上面是常量和 order_string。我想检查 order_string 是否包含任何从 '{' 或 '{{' 开始的子字符串,例如 {{first_name}},那么这个子字符串 {{first_name}} 必须在常量变量中。如果它不在列表中,则 order_string 包含无效的子字符串。 例如

order_string = "Hello, {first_name}} {{last_name}}, Thanks for purchasing. You order number is {{or_num}}."

在这里,您可以看到 order_string 变量包含子字符串 {first_name}} 和 {{or_num}},它们不存在于 constants 变量中。

我试过了

str_list = order_string.split()

for item in str_list:
    print(item)
    if re.search("({+|}+)", item):
        print('has format')
        if not item in constant:
            raise Exception() 

它适用于类似字符串

order_string = "Hello, {{first_name}} last_name}} .Your order number is {{order_num}}".

但是任何子字符串最后都包含点、逗号或任何字符都失败了。像这样

order_string = "Hello, {{first_name}} last_name}}. Your order number is {{order_num}}."

【问题讨论】:

  • 请提及预期的输入和输出。很难理解你想要什么。
  • 我已经更新了这个问题。如果仍有疑问,请告诉我。
  • order_string = " Hello, {{first_name}} {{last_name}}, Thanks for purchasing. You order number is {{order_num}} {{blah}} " exprs =re.findall(r'(\{\{[^}]+\}\})', order_string) print([e for e in exprs if e not in constants])
  • @shahkalpeshp 它只会过滤掉具有特定格式的内容。比如如果 order_string = "你好,{{first_name}} last_name}}。你的订单号是 {{order_num}}",那么 exprs = ['{{first_name}}', '{{order_num}}']。它没有捕获我需要的“last_name}}”,因为它的格式错误。

标签: python string list


【解决方案1】:

试试这个 -

order_string = " Hello, {{first_name}} {{last_name}}, Thanks for purchasing. You order number is {{order_num}} "

a = order_string.split()
a[2] = a[2].split(',')[0]

for i in a:
     if i in constants:
          print(i)

【讨论】:

    猜你喜欢
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 2023-04-01
    相关资源
    最近更新 更多