📜  Python程序将给定的字符大写

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

Python程序将给定的字符大写

给定一个字符串和字符集,将字符串中字符集出现的所有字符转换为大写()

方法 #1:使用循环 + upper()

以上功能的组合可以解决这个问题。在这里,我们使用循环检查每个字符,如果它在字符中,则使用 upper() 将其转换为大写。

Python3
# Python3 code to demonstrate working of 
# Uppercase custom characters
# Using upper() + loop
  
# initializing string
test_str = 'gfg is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing upperlist 
upper_list = ['g', 'e', 'b', 'k']
  
res = ''
for ele in test_str:
      
    # checking for presence in upper list 
    if ele in upper_list:
        res += ele.upper()
    else :
        res += ele
      
# printing result 
print("String after reconstruction : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Uppercase custom characters
# Using list comprehension
  
# initializing string
test_str = 'gfg is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing upperlist 
upper_list = ['g', 'e', 'b', 'k']
  
# one-liner used to solve problem
res = "".join([ele.upper() if ele in upper_list else ele for ele in test_str])
      
# printing result 
print("String after reconstruction : " + str(res))


输出
The original string is : gfg is best for geeks
String after reconstruction : GfG is BEst for GEEKs

方法#2:使用列表理解

这是可以执行此任务的另一种方式。在这种情况下,我们以与上述方法类似的方式执行任务,但作为使用单行列表理解的速记。

蟒蛇3

# Python3 code to demonstrate working of 
# Uppercase custom characters
# Using list comprehension
  
# initializing string
test_str = 'gfg is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing upperlist 
upper_list = ['g', 'e', 'b', 'k']
  
# one-liner used to solve problem
res = "".join([ele.upper() if ele in upper_list else ele for ele in test_str])
      
# printing result 
print("String after reconstruction : " + str(res))
输出
The original string is : gfg is best for geeks
String after reconstruction : GfG is BEst for GEEKs