[英]How do i check if one or more certain characters are an a string?
I want to check if two strings contain "\\n" or "\\r" using just one if statement not two, and is there any way to do this or must I use a for loop? 我想检查两个字符串是否仅使用一个if语句而不是两个包含“ \\ n”或“ \\ r”,并且有任何方法可以做到这一点,还是必须使用for循环?
I tried tweaking the if statement in many ways but it seems like I just cant get it right, so must I use a for loop or two if statements? 我尝试了多种方式来调整if语句,但似乎无法正确处理,因此必须使用for循环还是两个if语句?
def singleline_diff_format(line1, line2, idx):
"""
Inputs:
line1 - first single line string
line2 - second single line string
idx - index at which to indicate difference
Output:
Returns a three line formatted string showing the location
of the first difference between line1 and line2.
If either input line contains a newline or carriage return,
then returns an empty string.
If idx is not a valid index, then returns an empty string.
"""
equals = "=" * (idx)
min_length = min(len(line1), len(line2))
if "\n" or "\r" in line1 or line2:
return ""
else:
return line1 + "\n{}^".format(equals) + "\n" + line2
print(singleline_diff_format("abcd", "abed", 2))
print(singleline_diff_format("abcd \nhey man", "abed", 2))
print(singleline_diff_format("abcd", "abed", 5))
I expect 我预计
abcd A B C D
==^ == ^
abed 床
abcd A B C D
hey man 嗨,老兄
==^ == ^
abed 床
abcd A B C D
=====^ ===== ^
abed 床
But I just get empty strings which means that the if statement isn't working properly. 但是我只是得到空字符串,这意味着if语句不能正常工作。
if any(char in line for char in ('\n', '\r') for line in (line1, line2)):
....
This will be True
if any of the 4 conditions '\\n' in line1
, '\\n' in line2
, '\\r' in line1
, '\\r' in line2
is `True - and is much more compact... 这将是
True
,如果任何4个条件中'\\n' in line1
, '\\n' in line2
, '\\r' in line1
, '\\r' in line2
是'真-并且更加紧凑...
Your logic isn't doing what you intend and when you do match, you are returning an empty string. 您的逻辑没有按照您的预期进行,当您进行匹配时,您将返回一个空字符串。 if "\\n" or "\\r" in line1 or line2: return ""
如果第1行或第2行中为“ \\ n”或“ \\ r”,则返回“”
Try: if ("\\n" or "\\r") in (line1 or line2): return f'{line1}\\n=\\n{line2}' 尝试:如果(line1或line2)中的(“ \\ n”或“ \\ r”):返回f'{line1} \\ n = \\ n {line2}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.