用python找出两个字符串相同的部分
时间: 2023-06-09 16:03:06 浏览: 182
您好!很高兴为您服务,以下是您所需要的回答:
我们可以使用Python中的内置函数来找出两个字符串相同的部分,具体的实现如下:
```python
string1 = 'hello'
string2 = 'world'
result = ''
for i in string1:
if i in string2 and i not in result:
result += i
if result:
print(f"The matching characters are: {result}")
else:
print("There are no matching characters.")
```
在这个例子中,我们定义了两个字符串`string1`和`string2`,然后利用一个for循环遍历字符串`string1`的每个字符,判断它是否同时也存在于`string2`中,并且不存在于`result`中。如果是这样的话,就将这个字符添加到`result`中。最后,如果`result`不为空,则输出匹配到的字符,否则表示没有匹配到任何字符。
希望这个回答能够帮助您!
相关问题
找出两个字符串数组中的相同元素
可以使用两个 for 循环来比较两个字符串数组中的元素,如果两个元素相同,则将其添加到一个新的数组中:
```python
def find_common(str1, str2):
common = []
for s1 in str1:
for s2 in str2:
if s1 == s2:
common.append(s1)
return common
```
这个函数接受两个字符串数组作为输入参数,它会返回一个新的数组,其中包含两个输入数组中相同的元素。
用Python写一个程序,找出两个字符串中最长的相同的字符
好的,下面是一个简单的 Python 程序,可以找出两个字符串中最长的相同字符序列:
```python
def longest_common_substring(str1, str2):
m = len(str1)
n = len(str2)
# 创建一个二维数组来保存最长公共子串的长度
# 初始化为0
lcs = [[0] * (n + 1) for i in range(m + 1)]
# 记录最长公共子串的长度
max_length = 0
# 记录最长公共子串的结束位置
end_position = 0
# 填充数组
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i - 1] == str2[j - 1]:
lcs[i][j] = lcs[i - 1][j - 1] + 1
if lcs[i][j] > max_length:
max_length = lcs[i][j]
end_position = i
else:
lcs[i][j] = 0
# 返回最长公共子串
return str1[end_position - max_length:end_position]
# 测试代码
str1 = "abcdefg"
str2 = "defghijk"
print(longest_common_substring(str1, str2))
```
输出结果为:
```
defg
```
这个程序使用了动态规划算法来解决问题,时间复杂度为 O(mn),其中 m 和 n 分别为两个字符串的长度。