📜  Python|替换字符串列表中的子字符串

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

Python|替换字符串列表中的子字符串

在使用字符串时,最常用的应用程序之一是将字符串的一部分替换为另一个。由于字符串本身是不可变的,因此了解此实用程序本身就非常有用。这里执行字符串列表中子字符串的替换。让我们讨论可以执行此操作的某些方式。

方法 #1:使用列表理解 + replace()
replace 方法可以与列表理解技术相结合来完成这个特定的任务。列表推导执行遍历列表的任务,replace 方法用另一个替换子字符串部分。

# Python3 code to demonstrate
# Replace substring in list of strings
# using list comprehension + replace()
  
# initializing list 
test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks']
  
# printing original list  
print("The original list : " + str(test_list ))
  
# using list comprehension + replace()
# Replace substring in list of strings
res = [sub.replace('4', '1') for sub in test_list]
      
# print result
print("The list after substring replacement : " + str(res))
输出 :
The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']
The list after substring replacement : ['1', 'kg', 'butter', 'for', '10', 'bucks']

方法 #2:使用map() + lambda + replace()
这些功能的组合也可用于执行此特定任务。 map 和 lambda 帮助执行与列表理解相同的任务,并且 replace 方法用于执行替换功能。但是这种方法在性能方面比上面的方法差。

# Python3 code to demonstrate
# Replace substring in list of strings
# using list comprehension + map() + lambda
  
# initializing list 
test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks']
  
# printing original list  
print("The original list : " + str(test_list ))
  
# using list comprehension + map() + lambda
# Replace substring in list of strings
res = list(map(lambda st: str.replace(st, "4", "1"), test_list))
      
# print result
print("The list after substring replacement : " + str(res))
输出 :
The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']
The list after substring replacement : ['1', 'kg', 'butter', 'for', '10', 'bucks']