python判断数组中每个字符串结尾
时间: 2024-01-23 08:12:59 浏览: 21
要判断数组中每个字符串结尾,可以使用Python中的字符串方法`endswith()`。该方法接受一个字符串作为参数,判断当前字符串是否以该参数指定的字符串结尾。可以遍历数组中的每个字符串,然后依次调用`endswith()`方法进行判断。以下是示例代码:
```python
arr = ['hello world', 'python', 'apple', 'banana']
suffix = 'ld'
for s in arr:
if s.endswith(suffix):
print(s + ' ends with ' + suffix)
else:
print(s + ' does not end with ' + suffix)
```
输出结果为:
```
hello world ends with ld
python does not end with ld
apple does not end with ld
banana ends with ld
```
相关问题
用python实现去掉字符串数组中每个字符串的空格
可以使用以下代码来实现去掉字符串数组中每个字符串的空格:
```python
def remove_spaces(strings):
new_strings = []
for string in strings:
new_string = string.replace(" ", "")
new_strings.append(new_string)
return new_strings
# 示例用法
strings = ["hello world", " python ", " coding "]
new_strings = remove_spaces(strings)
print(new_strings)
```
在上述代码中,我们定义了一个名为 `remove_spaces` 的函数,它接受一个字符串数组作为参数。在函数内部,我们创建了一个新的空数组 `new_strings`,用于存储去掉空格后的每个字符串。然后,我们使用 `replace()` 方法将每个字符串中的空格替换为空字符,并将替换后的字符串添加到新数组 `new_strings` 中。最后,我们返回新数组。
在示例用法部分,我们定义了一个字符串数组 `strings`,其中包含了一些带有空格的字符串。然后,我们调用 `remove_spaces` 函数,并将返回的新数组存储在 `new_strings` 变量中。最后,我们输出 `new_strings` 的内容,即去掉空格后的字符串数组。
请注意,上述代码中使用了 `replace()` 方法来去掉空格。如果你想只去掉字符串开头和结尾的空格,可以使用 `strip()` 方法。
python找到两个字符串的共同子字符串
可以使用动态规划算法来解决这个问题。具体步骤如下:
1. 创建一个二维数组dp,其中dp[i][j]表示以第一个字符串的第i个字符结尾和以第二个字符串的第j个字符结尾的最长公共子字符串的长度。
2. 初始化dp数组的第一行和第一列为0。
3. 遍历第一个字符串和第二个字符串的每个字符,如果两个字符相等,那么dp[i][j] = dp[i-1][j-1] + 1;否则,dp[i][j] = 0。
4. 在遍历的过程中,记录下最长的公共子字符串的长度和位置。
5. 根据最长公共子字符串的长度和位置,从两个字符串中分别截取出公共子字符串。
下面是一个示例代码:
```
def find_common_substring(s1, s2):
m, n = len(s1), len(s2)
dp = [[0] * (n+1) for _ in range(m+1)]
max_len, end_pos = 0, 0
for i in range(1, m+1):
for j in range(1, n+1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
if dp[i][j] > max_len:
max_len = dp[i][j]
end_pos = i
else:
dp[i][j] = 0
return s1[end_pos-max_len:end_pos]
```
这个函数的参数是两个字符串s1和s2,返回值是它们的最长公共子字符串。