Python – 每第 K 个字符串大写
给定一个字符串列表,将每个第 K 个字符串更改为大写。
Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], K = 3
Output : [‘GFG’, ‘is’, ‘best’, ‘FOR’, ‘geeks’]
Explanation : All Kth strings are uppercased.
Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], K = 4
Output : [‘GFG’, ‘is’, ‘best’, ‘for’, ‘GEEKS’]
Explanation : All Kth strings are uppercased.
方法#1:使用循环+上()
在此,我们使用循环对所有字符串进行迭代,并且使用大写来执行大写,使用模运算符检测第 K 个索引。
Python3
# Python3 code to demonstrate working of
# Every Kth Strings Uppercase
# Using loop + upper()
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks", "and", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
res = []
for idx in range(len(test_list)):
# checking for Kth index
if idx % K == 0:
res.append(test_list[idx].upper())
else :
res.append(test_list[idx])
# printing result
print("The resultant String list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Every Kth Strings Uppercase
# Using list comprehension
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks", "and", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# shorthand to perform this task
res = [test_list[idx].upper() if idx % K == 0 else test_list[idx]
for idx in range(len(test_list))]
# printing result
print("The resultant String list : " + str(res))
输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'CS']
The resultant String list : ['GFG', 'is', 'best', 'FOR', 'geeks', 'and', 'CS']
方法#2:使用列表推导
这是可以执行此任务的另一种方式。在此我们使用列表推导作为简写,执行类似于上述方法的任务。
Python3
# Python3 code to demonstrate working of
# Every Kth Strings Uppercase
# Using list comprehension
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks", "and", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# shorthand to perform this task
res = [test_list[idx].upper() if idx % K == 0 else test_list[idx]
for idx in range(len(test_list))]
# printing result
print("The resultant String list : " + str(res))
输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'CS']
The resultant String list : ['GFG', 'is', 'best', 'FOR', 'geeks', 'and', 'CS']