是否存在使用for循环和if-else的Pythonic列表理解?
下面是一个列表理解,使用for循环将所有字符转换为uppe大小写是否存在使用for循环和if-else的Pythonic列表理解?,python,python-2.7,list-comprehension,Python,Python 2.7,List Comprehension,下面是一个列表理解,使用for循环将所有字符转换为uppe大小写 string = 'Hello' print "".join([s.upper() for s in string]) 下面是一个列表理解,只将小写字符转换为大写 print "".join([s.upper() for s in string if s.islower()]) 是否存在可以在字符串中交换大小写的列表理解?差不多 print "".join([s.upper() for s in string if s.isl
string = 'Hello'
print "".join([s.upper() for s in string])
下面是一个列表理解,只将小写字符转换为大写
print "".join([s.upper() for s in string if s.islower()])
是否存在可以在字符串中交换大小写的列表理解?差不多
print "".join([s.upper() for s in string if s.islower() else s.lower()])
下面是如何使用列表理解来实现这一点。请注意,当同时包含if/
else
和a时,语法必须如下所示:
condition\u if\u true if条件else condition\u if\u false
因此,在这种情况下,您可以执行以下操作:
string = 'Hello'
"".join([s.upper() if s.islower() else s.lower() for s in string])
# 'hELLO'
您只需要
string.swapcase()
您正在寻找s.swapcase()
?是的,swapcase。但这只是我选择的一个例子。想知道我是否可以在列表理解中使用for循环、if和else来仅将小写字符转换为大写字符。这是一个列表理解,只接受较低的字符并转换它们。“你好”变成了“你好”if
是列表理解中的一个过滤器也用于Python的三元语法检查:谢谢。这正是我想要的。在列表中使用for循环if/else的语法