Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python if语句中嵌套在表达式内的for循环_Python_Python 3.x - Fatal编程技术网

Python if语句中嵌套在表达式内的for循环

Python if语句中嵌套在表达式内的for循环,python,python-3.x,Python,Python 3.x,这是一个关于语法的问题。我很肯定我几乎是对的,但不是完全正确。我试图在if语句的表达式中放入for循环 我认为它应该是一个简单回文测试仪的模型: toTest = "asdffdsa" if toTest[i]==toTest[-i] for i in range(len(toTest)/2): print("It's a palendrome!") 提前感谢您的帮助 我想你是说 if all(toTest[i] == toTest[-i] for i in range(len(toT

这是一个关于语法的问题。我很肯定我几乎是对的,但不是完全正确。我试图在if语句的表达式中放入for循环

我认为它应该是一个简单回文测试仪的模型:

toTest = "asdffdsa"
if toTest[i]==toTest[-i] for i in range(len(toTest)/2):
    print("It's a palendrome!")
提前感谢您的帮助

我想你是说

if all(toTest[i] == toTest[-i] for i in range(len(toTest)/2)):
    print("It's a palindrome!")
请注意,这样做会容易得多

if toTest == toTest[::-1]:
    print("It's a palindrome!")

虽然它可能不完全是您想要的,但这里有一个简短的方法来检查字符串在Python中是否是回文:

toTest = "asdffdsa"
if toTest == toTest[::-1]: print ("It's a palindrome!")

我确实看过了,但是没有我要找的例子。谢谢!你刚刚回答了我的问题,教了我一个新的关键词。“toTest[:-1]”中的“-1”是否反转列表?@Mokolodi1:是的,它反转字符串,请参见。不是关键字<代码>全部是一个函数。