【问题标题】:Python prints parts that are not identical in two stringsPython 打印两个字符串中不相同的部分
【发布时间】:2023-03-19 05:44:01
【问题描述】:

我尝试做这样的事情:

a = "i am from Israel"
b = "i live in Switzerland"

输出:

"live", "am", "from", "Israel", "in", "Switzerland"

因为这些部分不会出现在两个字符串中。 我该怎么做?

【问题讨论】:

  • 显示代码。显示的内容不会产生任何输出。
  • 我写了我想让程序打印的东西
  • 听起来您想要一个名为 symmetric_differenceset 操作。
  • StackOverflow 不是编码服务。阅读链接并自己编写代码。如果您有问题,请发布代码。
  • 你是什么意思“所以”

标签: python-3.x string


【解决方案1】:

使用set()symetric difference

a = "i am from Israel"
b = "i live in Switzerland"
c = set(a.split()) ^ set(b.split())
print(c)

输出:

{'Israel', 'Switzerland', 'am', 'from', 'in', 'live'}

【讨论】:

    【解决方案2】:

    我喜欢这个挑战,这绝不是一个完美的答案,但这就是我想出的。

    a = "i am from Israel"
    b = "i live in Switzerland"
    
    a = a.split(" ")        # splitting the strings
    b = b.split(" ")
    
    for part in b:          # iterating over list
        try:
            a.remove(part)  # try to remove 
        except ValueError:  # if removing gives you an error it is not in it 
            a.append(part)  # add the part to list a
    
    print(a)
    

    为我输出: ['am', 'from', 'Israel', 'live', 'in', 'Switzerland']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      相关资源
      最近更新 更多