簡體   English   中英

檢查第一個和最后一個字符時出現 Python 字符串問題

[英]Python string issue when checking the first and last character

這是問題: - 修改 first_and_last function 以便如果字符串的第一個字母與字符串的最后一個字母相同則返回 True,如果它們不同則返回 False。 請記住,您可以使用 message[0] 或 message[-1] 訪問字符。 小心你如何處理空字符串,它應該返回 True,因為沒有什么等於沒有。

當我寫這樣的代碼時: -

def first_and_last(message):

    if len(message) == 0:
        return True
    elif message[0] == message[-1]:
        return True
    else:
        return False


print(first_and_last("else"))

print(first_and_last("tree"))

print(first_and_last(""))

# output:-

True

False 

True

但是當我寫這樣的代碼時: -

def first_and_last(message):

    if message[0] == message[-1]:
        return True
    elif len(message) == 0:
        return True
    else:
        return False

print(first_and_last("else"))

print(first_and_last("tree"))

print(first_and_last(""))

# output:-
True

False

Traceback (most recent call last):
  File "C:/Users/Sidje/PycharmProjects/untitled2/SId.py", line 11, in <module>
    print(first_and_last(""))
  File "C:/Users/Sidje/PycharmProjects/untitled2/SId.py", line 2, in first_and_last
    if message[0] == message[-1]:
IndexError: string index out of range

當我用 elif 編寫 len 函數時,當語句為空時程序不工作,但它適用於其他條件。 這是為什么?

在以下情況下(您的第二個代碼塊),“if”條件嘗試訪問沒有字符的字符串的第一個字符。 這會導致錯誤。

if message[0] == message[-1]:  # can't access 0th element if string is empty
    return True
elif len(message) == 0:
    return True
else:
    return False

在另一種情況下(您的第一個塊),此錯誤永遠不會發生,因為如果字符串沒有字符,則永遠不會達到該條件,因為自從滿足第一個條件后,“elif”被跳過。

if len(message) == 0:
    return True
elif message[0] == message[-1]:  # skipped if first condition was met
    return True
else:
    return False

'當您發送“(空)值時,您正在調用 function 消息 [0],消息 [-1] 無法在上述索引中找到值:

注意 if function 先執行,然后是剩余條件。

def first_and_last(message):
    while len(message)>0:
        if  message[0]==message[-1]:
            return True
        else:
            return False
    return True

print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))

真假真

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM