min: 84 max: 99 avg: 95 ,用python正则表达式拿到84付给min变量
时间: 2024-05-10 12:14:20 浏览: 17
可以使用re模块中的findall函数来获取字符串中的数字,然后取最小值赋给min变量。具体代码如下:
```python
import re
str = "min: 84 max: 99 avg: 95"
nums = re.findall(r'\d+', str) # 获取字符串中的数字
min = min(int(num) for num in nums) # 取最小值并赋给min变量
print(min) # 输出84
```
相关问题
使用正则表达式查找文”Python12345678”最长的数字字符串
以下是使用正则表达式查找字符串中最长数字字符串的代码示例:
```python
import re
text = "Python12345678"
pattern = r'\d+'
matches = re.findall(pattern, text)
longest_match = max(matches, key=len)
print("最长数字字符串:", longest_match)
```
在这个例子中,我们使用`re.findall`函数和正则表达式`\d+`来查找字符串中的所有数字字符串。然后,我们使用`max`函数和`len`函数找到最长的数字字符串,并将其打印出来。
输出结果为:
```
最长数字字符串: 12345678
```
这个例子中的正则表达式`\d+`表示匹配一个或多个数字,因此它可以匹配任何长度的数字字符串。如果您想要查找最短的数字字符串,可以使用`min`函数而不是`max`函数。
python正则表达式输入一字符串,各个子串之间按空白字符隔开,分别显式其中最长、最短子串,以及最大、最小字符。
可以使用re模块来实现正则表达式匹配。代码如下:
import re
# 输入字符串
s = input("请输入字符串:")
# 匹配所有非空白字符的子串
substrings = re.findall('\S+', s)
# 计算最长、最短子串
longest_substring = max(substrings, key=len)
shortest_substring = min(substrings, key=len)
# 计算最大、最小字符
all_chars = ''.join(substrings)
max_char = max(all_chars)
min_char = min(all_chars)
# 输出结果
print("最长子串:", longest_substring)
print("最短子串:", shortest_substring)
print("最大字符:", max_char)
print("最小字符:", min_char)
输入示例:
请输入字符串:abc defg hij
输出结果:
最长子串: defg
最短子串: abc
最大字符: j
最小字符: a
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)