Python – 过滤相似的大小写字符串
给定字符串列表,任务是编写一个Python程序来过滤所有具有相似大小写的字符串,无论是大写还是小写。
例子:
Input : test_list = [“GFG”, “Geeks”, “best”, “FOr”, “all”, “GEEKS”]
Output : [‘GFG’, ‘best’, ‘all’, ‘GEEKS’]
Explanation : GFG is all uppercase, best is all lowercase.
Input : test_list = [“GFG”, “Geeks”, “best”]
Output : [‘GFG’, ‘best’]
Explanation : GFG is all uppercase, best is all lowercase.
方法 #1:使用islower() + isupper() +列表理解
在这里,我们使用 islower() 和 isupper() 检查每个字符串是小写还是大写,并且使用列表理解来遍历字符串。
Python3
# Python3 code to demonstrate working of
# Filter Similar Case Strings
# Using islower() + isupper() + list comprehension
# initializing Matrix
test_list = ["GFG", "Geeks",
"best", "FOr", "all", "GEEKS"]
# printing original list
print("The original list is : " + str(test_list))
# islower() and isupper() used to check for cases
res = [sub for sub in test_list if sub.islower() or sub.isupper()]
# printing result
print("Strings with same case : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter Similar Case Strings
# Using islower() + isupper() + filter() + lambda
# initializing Matrix
test_list = ["GFG", "Geeks", "best",
"FOr", "all", "GEEKS"]
# printing original list
print("The original list is : " + str(test_list))
# islower() and isupper() used to check for cases
# filter() and lambda function used for filtering
res = list(filter(lambda sub : sub.islower() or sub.isupper(), test_list))
# printing result
print("Strings with same case : " + str(res))
输出:
The original list is : [‘GFG’, ‘Geeks’, ‘best’, ‘FOr’, ‘all’, ‘GEEKS’]
Strings with same case : [‘GFG’, ‘best’, ‘all’, ‘GEEKS’]
方法#2:使用islower() + isupper() + filter() + lambda
在此,我们使用 filter() 和 lambda函数执行过滤字符串的任务。其余所有功能与上述方法类似。
蟒蛇3
# Python3 code to demonstrate working of
# Filter Similar Case Strings
# Using islower() + isupper() + filter() + lambda
# initializing Matrix
test_list = ["GFG", "Geeks", "best",
"FOr", "all", "GEEKS"]
# printing original list
print("The original list is : " + str(test_list))
# islower() and isupper() used to check for cases
# filter() and lambda function used for filtering
res = list(filter(lambda sub : sub.islower() or sub.isupper(), test_list))
# printing result
print("Strings with same case : " + str(res))
输出:
The original list is : [‘GFG’, ‘Geeks’, ‘best’, ‘FOr’, ‘all’, ‘GEEKS’]
Strings with same case : [‘GFG’, ‘best’, ‘all’, ‘GEEKS’]