Python – 大写半字符串
给定一个字符串,执行字符串后面部分的大写。
Input : test_str = ‘geeksforgeek’
Output : geeksfORGEEK
Explanation : Latter half of string is uppercased.
Input : test_str = ‘apples’
Output : appLES
Explanation : Latter half of string is uppercased.
方法#1:使用upper() + loop + len()
在此,我们计算半索引,然后仅对位于字符串另一半的字符执行 upper()。
Python3
# Python3 code to demonstrate working of
# Uppercase Half String
# Using upper() + loop + len()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# computing half index
hlf_idx = len(test_str) // 2
res = ''
for idx in range(len(test_str)):
# uppercasing later half
if idx >= hlf_idx:
res += test_str[idx].upper()
else :
res += test_str[idx]
# printing result
print("The resultant string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Uppercase Half String
# Using list comprehension + join() + upper()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# computing half index
hlf_idx = len(test_str) // 2
# join() used to create result string
res = ''.join([test_str[idx].upper() if idx >= hlf_idx else test_str[idx]
for idx in range(len(test_str)) ])
# printing result
print("The resultant string : " + str(res))
输出
The original string is : geeksforgeeks
The resultant string : geeksfORGEEKS
方法#2:使用列表理解 + join() + upper()
这类似于上述方法,只是使用列表推导以简写方式执行任务。
Python3
# Python3 code to demonstrate working of
# Uppercase Half String
# Using list comprehension + join() + upper()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# computing half index
hlf_idx = len(test_str) // 2
# join() used to create result string
res = ''.join([test_str[idx].upper() if idx >= hlf_idx else test_str[idx]
for idx in range(len(test_str)) ])
# printing result
print("The resultant string : " + str(res))
输出
The original string is : geeksforgeeks
The resultant string : geeksfORGEEKS