Python程序在给定条件下将字符串转换为大写
给定一个字符串列表,任务是编写一个Python程序来在长度大于 K 时转换大写字符串。
例子:
Input : test_list = [“Gfg”, “is”, “best”, “for”, “geeks”], K = 3
Output : [‘Gfg’, ‘is’, ‘BEST’, ‘for’, ‘GEEKS’]
Explanation : Best has 4 chars, hence BEST is uppercased.
Input : test_list = [“Gfg”, “is”, “best”, “for”, “geeks”], K = 4
Output : [‘Gfg’, ‘is’, ‘best’, ‘for’, ‘GEEKS’]
Explanation : geeks has 5 chars [greater than 4], hence GEEKS is uppercased.
方法 #1:使用upper() +循环
在此,我们使用 upper() 执行大写任务,并使用循环检查更大的条件语句。
Python3
# Python3 code to demonstrate working of
# Conditional Uppercase by size
# Using upper() + loop
# initializing list
test_list = ["Gfg", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
res = []
for ele in test_list:
# check for size
if len(ele) > K:
res.append(ele.upper())
else:
res.append(ele)
# printing result
print("Modified Strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Conditional Uppercase by size
# Using list comprehension
# initializing list
test_list = ["Gfg", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# list comprehension for one liner solution
res = [ele.upper() if len(ele) > K else ele for ele in test_list]
# printing result
print("Modified Strings : " + str(res))
输出:
The original list is : ['Gfg', 'is', 'best', 'for', 'geeks']
Modified Strings : ['Gfg', 'is', 'BEST', 'for', 'GEEKS']
方法#2:使用列表理解
在这种情况下,迭代任务在列表理解中执行,以作为与上述类似方法的速记。
蟒蛇3
# Python3 code to demonstrate working of
# Conditional Uppercase by size
# Using list comprehension
# initializing list
test_list = ["Gfg", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# list comprehension for one liner solution
res = [ele.upper() if len(ele) > K else ele for ele in test_list]
# printing result
print("Modified Strings : " + str(res))
输出:
The original list is : ['Gfg', 'is', 'best', 'for', 'geeks']
Modified Strings : ['Gfg', 'is', 'BEST', 'for', 'GEEKS']