📜  Python – 字符串列表中的特定情况变化

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

Python – 字符串列表中的特定情况变化

在使用字符串列表时,大小写问题很常见,但有时我们会担心选择性地更改字符串中的大小写。即基于其他列表。这可以在日常编程中应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环+ upper() + enumerate()
这是可以执行此任务的方式之一。在此我们为每个元素运行一个循环并比较字符串,如果发现相等,则这些列表的情况不会改变,其余字符串情况会改变。

# Python3 code to demonstrate 
# Specific case change in String List
# using loop + upper() + enumerate() 
  
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Specific case change in String List
# using loop + upper() + enumerate() 
for idx, ele in enumerate(test_list1):
    for ele2 in test_list2:
        if ele == ele2.upper():
            test_list1[idx] = ele2
              
# printing result 
print ("The string list after case change is : " + str(test_list1))
输出 :
The original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']

方法#2:使用循环+ capitalize()
此方法的执行与上述方法类似,不同之处在于使用 capitalize() 代替 upper() 来执行更改大小写的任务。

# Python3 code to demonstrate 
# Specific case change in String List
# using loop + capitalize()
  
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Specific case change in String List
# using loop + capitalize()
for idx, ele in enumerate(test_list1):
  if ele.capitalize() in test_list2:
    test_list1[idx] = ele.capitalize()
              
# printing result 
print ("The string list after case change is : " + str(test_list1))
输出 :
The original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']