把一个list中所有的字符串变成小写 |
您所在的位置:网站首页 › python如何将字符串转换为小写 › 把一个list中所有的字符串变成小写 |
L = ['Hello', 'World', 'IBM', 'Apple'] [s.lower() for s in L] ['hello', 'world', 'ibm', 'apple'] 如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错 使用内建的isinstance函数可以判断一个变量是不是字符串: >>> x = 'abc' >>> y = 123 >>> isinstance(x, str) True >>> isinstance(y, str) False修改列表生成式,通过添加if语句保证列表生成式能正确地执行 L1 = ['Hello', 'World', 18, 'Apple', None] L2=[x.lower() for x in L1 if isinstance(x,str)] print(L2)originated L1 = ['Hello', 'World', 18, 'Apple', None] L2=[x.lower for L1[x] in L1 if isinstance(L1[x],str)==True] #x.lower()函数的正确书写形式 #L1[x]---x本身表示的就是L1中的元素,不是索引 因此后面的isinstance(x,str) #if *** 直接表示为真,没有必要==True print(L2)
|
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |