Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,如何在引号内检查字符串中的某些字符_Python_String - Fatal编程技术网

在python中,如何在引号内检查字符串中的某些字符

在python中,如何在引号内检查字符串中的某些字符,python,string,Python,String,我需要检查某些字符,例如[!,:]是否在字符串中的引号内,而不是在引号外 The quick "brown!" fox jumps ":over" the lazy dog - valid string The quick! "brown!" fox jumps ":over" the lazy, dog - invalid string 如何检查此项?您可能想检查,这项功能在这方面非常强大 import re ifvalid = False chars = ['!', ',', ':']

我需要检查某些字符,例如[!,:]是否在字符串中的引号内,而不是在引号外

The quick "brown!" fox jumps ":over" the lazy dog - valid string
The quick! "brown!" fox jumps ":over" the lazy, dog - invalid string
如何检查此项?

您可能想检查,这项功能在这方面非常强大

import re

ifvalid = False
chars = ['!', ',', ':']
str1 = 'The quick "brown!" fox jumps ":over" the lazy dog - valid string'

nonquote = re.split('["].+?["]', str1)
quote = re.findall('["].+?["]', str1)

for word in quote:
    for ch in word:
        if ch in chars:
            ifvalid = True

for word in nonquote:
    for ch in word:
        if ch in chars:
            ifvalid = False

if ifvalid:
    print 'valid'
else:
    print 'invalid'
你用过吗

您可以删除所有带引号的单词并查找您的标记

import re

def all_tokens_quoted(string):
    quoted_words = re.compile('".*?"')
    tokens = re.compile('[!,:]')
    no_quotations = quoted_words.sub('', string)
    if tokens.search(no_quotations):
        return False
    return True

all_tokens_quoted('The quick "brown!" fox jumps ":over" the lazy dog')
>>> True
all_tokens_quoted('The quick! "brown!" fox jumps ":over" the lazy, dog')
>>> False

如果没有正则表达式,请尝试以下操作:

text = 'The quick "brown!" fox jumps ":over" the lazy dog'
text = text.split('"')
quotes = [text[i] for i in range (len(text)) if (i % 2 == 1)]
not_quotes = [text[i] for i in range (len(text)) if (i % 2 == 0)]
print(quotes, not_quotes)
这将提供正确的输出:

['brown!', ':over'] ['The quick ', ' fox jumps ', ' the lazy dog']
然后,您可以将其中的每一个拆分为一个字符串,并查看它们是否包含字符

valid = True #assume valid

for not_quote in not_quotes:
    characters = list(not_quote)
    for character in characters:
        if character in ['!',',',':']:
            valid = False

可以对引号中的字符串执行类似的验证。

用双引号拆分字符串,然后检查您的字符是否在奇数字符串中?很抱歉,这不是我所期望的。这段代码应该检查字符是否在引号内,但我需要检查字符串中是否有这些字符,它们应该只在引号内。@МааааПааааааааааааа107。
str1 = "The quick \"brown!\" fox jumps \":over\" the lazy dog - valid string"
str1_split = str1.split("\"")
for str in str1_split[1::2]:
    if str.find("!")>0:
        print "Found!"
        break