大写选择性索引的Python程序
给定一个字符串,对特定索引执行大写。
Input : test_str = ‘geeksgeeksisbestforgeeks’, idx_list = [5, 7, 3, 2, 6, 9]
Output : geEKsGEEkSisbestforgeeks
Explanation : Particular indices are uppercased.
Input : test_str = ‘geeksgeeksisbestforgeeks’, idx_list = [5, 7, 3]
Output : geeKsGeEksisbestforgeeks
Explanation : Particular indices are uppercased.
方法 #1:使用循环 + upper()
在此,我们使用 upper() 执行转换为大写的任务,并将列表中的检查索引转换为大写。
Python3
# Python3 code to demonstrate working of
# Uppercase selective indices
# Using loop + upper()
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing indices list
idx_list = [5, 7, 3, 2, 6, 9]
res = ''
for idx in range(0, len(test_str)):
# checking for index list for uppercase
if idx in idx_list:
res += test_str[idx].upper()
else:
res += test_str[idx]
# printing result
print("Transformed String : " + str(res))
Python3
# Python3 code to demonstrate working of
# Uppercase selective indices
# Using list comprehension + upper() + join()
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing indices list
idx_list = [5, 7, 3, 2, 6, 9]
# one-liner way to solve this problem
res = ''.join([test_str[idx].upper() if idx in idx_list else test_str[idx]
for idx in range(0, len(test_str))])
# printing result
print("Transformed String : " + str(res))
输出
The original string is : geeksgeeksisbestforgeeks
Transformed String : geEKsGEEkSisbestforgeeks
方法 #2:使用列表理解+ upper() + join()
与上面类似的方法,区别在于列表理解用于提供一个 liner,而 join() 用于转换回字符串。
蟒蛇3
# Python3 code to demonstrate working of
# Uppercase selective indices
# Using list comprehension + upper() + join()
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing indices list
idx_list = [5, 7, 3, 2, 6, 9]
# one-liner way to solve this problem
res = ''.join([test_str[idx].upper() if idx in idx_list else test_str[idx]
for idx in range(0, len(test_str))])
# printing result
print("Transformed String : " + str(res))
输出
The original string is : geeksgeeksisbestforgeeks
Transformed String : geEKsGEEkSisbestforgeeks