python - 与另一个字符串进行比较时,如何从 Python 中的字符串中提取唯一的子字符串?
问题描述
我有两个字符串,说'a'和'b'。我想比较'a'和'b'并只提取'a'的独特部分。我可以简单地检查“b”是否在 a 中并提取。但这里的问题是,字符串 'a' 或 'b' 随机忽略了空格,因此有点困难。
这是我到目前为止所做的
a = "catsand dogs some other strings"
b = "cats and dogs"
a_no_space = a.replace(" ", "")
b_no_space = b.replace(" ", "")
if(b_no_space in a_no_space and len(a_no_space) > len(b_no_space)):
unique = a[b_no_space.index(b_no_space)+len(b_no_space):]
使用此解决方案,我得到以下结果
s some other strings
一开始我不想要那个's'。如何在 python 中解决这个问题?在这里使用正则表达式有帮助吗?如果有怎么办?
解决方案
这是一个根据子字符串的字母逐步分割较大字符串的解决方案:
idx = 0
if len(a) > len(b):
for letter in b:
if letter in a and letter != " ":
a= a[a.index(letter) + 1:]
print(a)
else:
for letter in a:
if letter in b and letter != " ":
b= b[b.index(letter) + 1:]
print(b)
推荐阅读
- algorithm - Reelgood 等流媒体聚合器如何搜索和发布?
- xamarin - 如何使用 Xamarin Forms 中的按钮打开手机上安装的 Slack 应用程序?
- javascript - 这个 .find 函数有什么根本错误吗?(猫鼬)
- java - Recyclerview 中的对话框 - IllegalStateException:指定的子级已经有父级
- python - 使用 Oauth2 登录 Google Colab
- python - 按下一个键激活键盘记录器并让它运行一段时间
- node.js - 只在MongoDB中存储时间
- r - 具有不完整和不规则时间变量的组滞后值
- centos7 - 另一个 Linux 用户的无限权限
- c# - 如何为 Outlook 约会设置时区。如果通过 EWS API 创建时