python基本大小写字符串
我试图将给定字符串中的所有大写字符改为小写,反之亦然python基本大小写字符串,python,string,list-comprehension,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
- 我做错了什么,为什么我的代码不能工作
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']
如果是s.lower()
则情况不好,因为它只是降低字符数的函数,与如果是s.lower()
相同。改用s.isupper()
>>> print result = list((s.lower() if s.isupper() else s.upper() for s in string))
['h', 'E', 'l', 'l', 'o']
你对发电机的逻辑是错误的:
s.upper()如果是s.lower(),则表示字符串中的s;如果是s.upper(),则表示字符串中的s;
s.lower()
第一部分是带条件的发电机-如果s.lower(),则除了之外,它是正常的
第二部分是发电机
现在第一台发电机的情况很复杂(如果
…和
…)已经有了一种方法
s = 'HelLo'
print(s.swapcase())
'hELlO'
我做错了什么,为什么我的代码不能工作
虽然好的python代码看起来像(可执行的)伪代码,读起来也像英语,但仅仅用英语陈述你想做的事情并期望python做正确的事情是行不通的。;-)
特别是中的关键字和
s.upper() for s in string if s.lower() and s.lower() for s in string if s.upper()
不会做你可能认为会做的事和
是一个布尔运算符,其工作原理如下:
True and True == True
True and False == False
False and True == False
False and False == False
在字符串上使用它(正如您在这里所做的)将产生一个可能令人惊讶的结果:
"foo" and "bar" == "bar"
"" and "bar" == ""
请参阅其他答案,了解该做什么。您正在对s.lower()使用布尔测试,该测试始终为True,因此您总是执行s.lower()测试operation@BlivetWidget所以如果s.lower()为真(意味着如果字符是小写的),那么我们会将它们改为s.upper?这行不就是这么做的吗:如果s.lower()@xi_uu谢谢你。但是再一次,你能解释一下我的代码一步一步地在做什么吗?比如我的逻辑有什么问题originally@Angular,s.lower()不判断字符串是否为小写。它使字符串变为小写。因为这不是一个空字符串,它将计算为布尔真。哦。。。哈哈,我试着用简单的英语来表达python逻辑。。。失败谢谢