[英]How do i check if one or more certain characters are an a string?
我想检查两个字符串是否仅使用一个if语句而不是两个包含“ \\ n”或“ \\ r”,并且有任何方法可以做到这一点,还是必须使用for循环?
我尝试了多种方式来调整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))
我预计
A B C D
== ^
床
A B C D
嗨,老兄
== ^
床
A B C D
===== ^
床
但是我只是得到空字符串,这意味着if语句不能正常工作。
您可以使用任何 :
if any(char in line for char in ('\n', '\r') for line in (line1, line2)):
....
这将是True
,如果任何4个条件中'\\n' in line1
, '\\n' in line2
, '\\r' in line1
, '\\r' in line2
是'真-并且更加紧凑...
您的逻辑没有按照您的预期进行,当您进行匹配时,您将返回一个空字符串。 如果第1行或第2行中为“ \\ n”或“ \\ r”,则返回“”
尝试:如果(line1或line2)中的(“ \\ n”或“ \\ r”):返回f'{line1} \\ n = \\ n {line2}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.