📜  Python程序在给定条件下将字符串转换为大写

📅  最后修改于: 2022-05-13 01:55:06.222000             🧑  作者: Mango

Python程序在给定条件下将字符串转换为大写

给定一个字符串列表,任务是编写一个Python程序来在长度大于 K 时转换大写字符串。

例子:

方法 #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']