📜  Python|两个字符串中的联合操作

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

Python|两个字符串中的联合操作

字符串操作之一可以是计算两个字符串的并集。这可能是可以处理的有用应用程序。本文通过不同的方式处理相同的计算。

方法1:朴素方法
执行字符串联合的任务可以通过简单的方法来计算,方法是创建一个空字符串并检查字符串和非公共字符串共有的新出现的字符并将其附加,从而计算新的联合字符串。这可以通过循环和 if/else 语句来实现。

# Python 3 code to demonstrate 
# Union Operation in two Strings
# using naive method 
  
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
  
# Printing initial strings
print ("The original string 1 is : " + test_str1)
print ("The original string 2 is : " + test_str2)
  
# using naive method to
# Union Operation in two Strings
res = ""
temp = test_str1
for i in test_str2:
    if i not in temp:
        test_str1 += i
          
# printing result
print ("The string union is : " + test_str1)
输出 :
The original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : GeeksforGeeksCda

方法 2:使用set() + union()
Python中的set通常可以执行set union等集合操作的任务。这个集合实用程序也可用于执行此任务。首先,使用 set() 将两个字符串转换为集合,然后使用 union() 执行联合。返回排序后的集合。

# Python 3 code to demonstrate 
# Union Operation in two Strings
# using set() + union()
  
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
  
# Printing initial strings
print ("The original string 1 is : " + test_str1)
print ("The original string 2 is : " + test_str2)
  
# using set() + union() to
# Union Operation in two Strings
res = set(test_str1).union(test_str2)
          
# printing result
print ("The string union is : " + str(res))
输出 :
The original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : {'s', 'G', 'r', 'e', 'o', 'f', 'k', 'C', 'd', 'a'}