python判断字符串是.png或者.jpg结尾
时间: 2024-02-24 18:55:17 浏览: 15
你可以使用字符串的`endswith()`方法来判断一个字符串是否以某个子串结尾。例如:
```
filename = "picture.png"
if filename.endswith(".png") or filename.endswith(".jpg"):
print("文件格式正确")
else:
print("文件格式不正确")
```
在上述代码中,`endswith()`方法用来判断`filename`字符串是否以`.png`或`.jpg`结尾,如果是,则输出"文件格式正确",否则输出"文件格式不正确"。
相关问题
python中字符串按.分开
可以使用字符串的split方法来将字符串按指定的分隔符分开,例如按"."分隔字符串可以这样写:
```
s = "python中字符串按.分开"
parts = s.split(".")
print(parts)
```
输出结果为:
```
['python中字符串按', '分开']
```
其中,split方法的返回结果是一个列表,包含了按"."分隔后的所有子串。
python判断字符串都是数字或者小数点
你可以使用 Python 中的 isdigit() 和 isdecimal() 方法来判断一个字符串是否都是数字,但是这两种方法都不能判断小数点。如果你需要同时判断小数点,可以使用正则表达式来实现。
以下是一个使用正则表达式来判断字符串是否都是数字或小数点的示例代码:
```python
import re
def is_number(str):
pattern = re.compile(r'^\d+(\.\d+)?$')
return pattern.match(str) is not None
```
这个函数会返回 True 如果字符串是一个数字或小数点,否则返回 False。