📜  Python – 字符串中的大写选择性子字符串

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

Python – 字符串中的大写选择性子字符串

给定一个字符串,对 List 中的特定子字符串执行大写。

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