我想只使用一个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))
我希望
abcd
== ^
abed
abcd
嘿男人
== ^
abed
abcd
===== ^
abed
但是我只是得到空字符串,这意味着if语句不能正常工作。
答案 0 :(得分:0)
您可以使用any:
if any(char in line for char in ('\n', '\r') for line in (line1, line2)):
....
如果四个条件True
,'\n' in line1
,'\n' in line2
,'\r' in line1
中的任何一个为True,则为'\r' in line2
-并且紧凑得多。 ..
答案 1 :(得分:0)
您的逻辑没有满足您的预期,当您进行匹配时,您将返回一个空字符串。 如果第1行或第2行为“ \ n”或“ \ r”: 返回“”
尝试: 如果(第1行或第2行)中的(“ \ n”或“ \ r”): 返回f'{line1} \ n = \ n {line2}'