python基本的大写和小写字符串

时间:2015-10-10 16:28:48

标签: python string list-comprehension

我正在尝试将给定字符串中的所有大写字符更改为小写,反之亦然。

  • 我做错了什么,为什么我的代码不工作?

所以我试图遍历每个字母(这是s)并将其更改为高位(如果它更低)和“反之亦然。”

string='HeLLO'

result=list(s.upper() for s in string if s.lower() and s.lower() for s in string if s.upper())

print(result)

output: ['H', 'E', 'L', 'L', 'O', 'H', 'E', 'L', 'L', 'O', 'H', 'E', 'L', 'L', 'O', 'H', 'E', 'L', 'L', 'O', 'H', 'E', 'L', 'L', 'O']

3 个答案:

答案 0 :(得分:4)

if s.lower()条件不好,因为它只是降低字符的功能,与if s.upper()相同。请改用s.isupper()

>>> print result = list((s.lower() if s.isupper() else s.upper() for s in string))
['h', 'E', 'l', 'l', 'o']

你的生成器逻辑是错误的:

  

s.upper()for s in string if s.lower() and s.lower()for s in string in string in s.upper()

第一部分是具有条件的生成器 - 除了if s.lower()之外它是可以的。

第二部分也是发电机。

现在它只是第一个生成器的复杂条件(if ... and ...)

答案 1 :(得分:3)

已经有了一种方法。

s = 'HelLo'
print(s.swapcase())

'hELlO'

答案 2 :(得分:1)

  

我做错了什么,为什么我的代码不起作用?

虽然好的python代码看起来像(可执行的)伪代码并且读起来很像英语,但只是说明你想要用英语做什么并期望Python做正确的事情是行不通的。 ; - )

特别是

中的关键字and
s.upper() for s in string if s.lower() and s.lower() for s in string if s.upper()

不会做你认为它会做的事情。 and是一个布尔运算符,其工作方式如下:

True and True == True
True and False == False
False and True == False
False and False == False

在字符串上使用它(就像你在这里一样)会产生令人惊讶的结果:

"foo" and "bar" == "bar"
"" and "bar" == ""

请参阅其他答案。