python判断字符串结尾
时间: 2023-11-22 21:04:30 浏览: 56
可以使用字符串的 `endswith()` 方法来判断一个字符串是否以指定的后缀结尾。
示例代码:
```python
str1 = "hello world"
if str1.endswith("world"):
print("字符串以 world 结尾")
else:
print("字符串不以 world 结尾")
```
输出结果:
```
字符串以 world 结尾
```
`endswith()` 方法也支持检查多个后缀,只需要将后缀作为一个元组传递给方法即可。例如:
```python
str1 = "hello world"
if str1.endswith(("world", "Python")):
print("字符串以 world 或 Python 结尾")
else:
print("字符串不以 world 或 Python 结尾")
```
输出结果:
```
字符串以 world 或 Python 结尾
```
相关问题
python123判断字符串结尾
你可以使用字符串的 `endswith` 方法来判断一个字符串是否以另一个字符串结尾。例如,假设你要判断字符串 `s` 是否以字符串 `end` 结尾,可以使用以下代码:
```python
if s.endswith('end'):
print('字符串s以end结尾')
else:
print('字符串s不以end结尾')
```
如果需要判断多个可能的结尾,也可以将它们放在一个元组中传给 `endswith` 方法,例如:
```python
if s.endswith(('end', 'suffix', 'termination')):
print('字符串s以多个可能的结尾之一结尾')
else:
print('字符串s不以这些结尾之一结尾')
```
python判断字符串以什么结尾
可以使用字符串的 `endswith()` 方法来判断一个字符串是否以指定的另一个字符串结尾。示例代码如下:
```python
s = 'hello world'
if s.endswith('world'):
print('s ends with "world"')
if s.endswith('python'):
print('s ends with "python"')
```
输出结果为:
```
s ends with "world"
```