Python 在给定字符串中将空字符串返回为True
如果字符串为空,我想返回Python 在给定字符串中将空字符串返回为True,python,python-3.x,string,Python,Python 3.x,String,如果字符串为空,我想返回True,如果字符串的第一个和最后一个字母匹配,我想返回True,如果字符串的第一个和最后一个字母不匹配,我想返回False,但是我已经编写了关于两种情况的代码,但我不知道如何将空字符串作为True,请协助。使用: def first_and_last(message): if (message[0] == message[3]): return True elif (message[0] != message[3]
True
,如果字符串的第一个和最后一个字母匹配,我想返回True
,如果字符串的第一个和最后一个字母不匹配,我想返回False
,但是我已经编写了关于两种情况的代码,但我不知道如何将空字符串作为True,请协助。使用:
def first_and_last(message):
if (message[0] == message[3]):
return True
elif (message[0] != message[3]):
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
如果字符串为空,则返回true:
if not message:
您可以使用
if not message:
检查message变量是否为空
例如,您可以执行以下操作:
def first_和def last(消息):
如果没有,请发送消息:
返回真值
elif(消息[0]==消息[3]):
返回真值
elif(消息[0]!=消息[3]):
返回错误
打印(第一个和最后一个(“其他”))
打印(第一个和最后一个(“树”))
打印(第一个和最后一个(“”)
您可以使用bool(message)
检查字符串是否为空。并用消息[-1]
检查最后一项:
def first_and_last(message):
if not message:
return True
if (message[0] == message[3]):
return True
elif (message[0] != message[3]):
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
- 你写了你想比较第一个字符和最后一个字符,
所以你必须使用
,而不是[-1]
。否则你就是在比较 第一个和第四个字符[3]
- 您可以使用
检查它是否为空字符串if not message
- 因为您要返回,所以不需要检查它们是否不匹配
如评论中所述,可以将其进一步压缩到一行中:
def first_and_last(message):
if not message:
return True
return message[0] == message[-1]
如果没有,您可以使用
def first_and_last(message):
return not message or message[0] == message[-1]
这里,
message==”
检查空字符串和后面的“或”它检查单词的第一个和最后一个字母。if(message=''):return True
是一个选项。你觉得怎么样?你想和最后一个还是第四个比较?如果是前者,则应使用[-1]
而不是[3]
。如果使用[3]
,则如果布尔(…)是冗余的,则第一个和最后一个(“abcad”)
将返回True
。只要如果没有消息
就足够了,不要硬编码[3]
,因为OP想要第一个和最后一个字符,请使用[-1]
hello@DeepSpace谢谢你的建议我是python新手,所以刚刚开始:)我不会硬编码[3]
,因为OP想要第一个和最后一个字符,请使用[-1]
不要硬编码[3]
,因为OP需要第一个和最后一个字符,请使用[-1]
@DeepSpace我不硬编码[3]。我收回了作者提供的解决问题的代码。我认为没有必要对答案中的所有帖子进行注释以注意相同的事情。但是,您可以完全通知帖子的作者,python列表/str…中的最后一个字符是由[-1]返回的
调用。为什么不使用:不返回消息或消息[0]==message[-1]
?这也返回布尔值!@ajizero完全正确(我将添加它),我最初觉得它有点太过用力了much@DeepSpace如果您可以帮助abel解决这个问题,请也研究一下这个问题,并欢迎使用stack overflow。请您的答案解释一下这个答案是如何改进其他答案的?
def first_and_last(message):
return not message or message[0] == message[-1]
def first_and_last(message):
if not message:
return False
else: return True
print(first_and_last("else")) #True
print(first_and_last("tree")) #True
print(first_and_last("")) #False
def first_and_last(message):
if not message:
return True
elif (message[0] == message[-1]):
return True
elif (message[0] != message[-1]):
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
def first_and_last(message):
if message=="" or message[0]==message[-1]:
return True
return False