【问题标题】:Python string issue when checking the first and last character检查第一个和最后一个字符时的Python字符串问题
【发布时间】:2021-01-02 14:53:25
【问题描述】:

这是问题:- 修改 first_and_last 函数,如果字符串的第一个字母与字符串的最后一个字母相同,则返回 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 函数时,当语句为空时程序不工作,但它适用于其他条件。 这是为什么呢?

【问题讨论】:

  • 这就是为什么它说Be careful how you handle the empty string
  • 啊,现在明白了:)

标签: python string


【解决方案1】:

在以下情况(您的第二个代码块)中,“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

【讨论】:

  • 非常感谢您的快速回复,我明白了:)
【解决方案2】:

'当您发送“(空)值时,您正在调用函数 message[0],message[-1] 无法在提到的索引中找到值:

注意 if 函数首先执行,然后是其余条件。'

【讨论】:

  • 谢谢老兄,现在明白了:)
猜你喜欢
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
相关资源
最近更新 更多