Python – 字符串中的大写选择性子字符串
给定一个字符串,对 List 中的特定子字符串执行大写。
Input : test_str = ‘geeksforgeeks is best for cs’, sub_list = [“best”, “geeksforgeeks”]
Output : GEEKSFORGEEKS is BEST for cs
Explanation : geeksforgeeks and best uppercased.
Input : test_str = ‘geeksforgeeks is best for best’, sub_list = [“best”, “geeksforgeeks”]
Output : GEEKSFORGEEKS is BEST for BEST
Explanation : geeksforgeeks and best both occurrences uppercased.
方法#1:使用 split() + join() + loop
在此,我们反复将字符串按子字符串拆分,然后在将字符串与大写版本的子字符串连接后执行连接操作。这仅在字符串中出现 1 次子字符串的情况下是成功的。
Python3
# Python3 code to demonstrate working of
# Uppercase Selective Substrings in String
# Using split() + join() + loop
# initializing strings
test_str = 'geeksforgeeks is best for cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing substrings
sub_list = ["best", "cs", "geeksforgeeks"]
for sub in sub_list:
# splitting string
temp = test_str.split(sub, -1)
# joining after uppercase
test_str = sub.upper().join(temp)
# printing result
print("The String after uppercasing : " + str(test_str))
Python3
# Python3 code to demonstrate working of
# Uppercase Selective Substrings in String
# Using re.sub() + upper()
import re
# initializing strings
test_str = 'geeksforgeeks is best for cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing substrings
sub_list = ["best", "cs", "geeksforgeeks"]
# constructing regex
reg = '|'.join(sub_list)
res = re.sub(reg, lambda ele: ele.group(0).upper(), test_str)
# printing result
print("The String after uppercasing : " + str(res))
输出
The original string is : geeksforgeeks is best for cs
The String after uppercasing : GEEKSFORGEEKS is BEST for CS
方法#2:使用 re.sub() + upper()
这使用正则表达式来解决这个问题。在此,我们使用适当的正则表达式,并对找到的字符串执行大写。
Python3
# Python3 code to demonstrate working of
# Uppercase Selective Substrings in String
# Using re.sub() + upper()
import re
# initializing strings
test_str = 'geeksforgeeks is best for cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing substrings
sub_list = ["best", "cs", "geeksforgeeks"]
# constructing regex
reg = '|'.join(sub_list)
res = re.sub(reg, lambda ele: ele.group(0).upper(), test_str)
# printing result
print("The String after uppercasing : " + str(res))
输出
The original string is : geeksforgeeks is best for cs
The String after uppercasing : GEEKSFORGEEKS is BEST for CS