编写python代码实现 输入一字符串,各个子串之间按空白字符隔开,分别显示其中最长、最短子串,以及最大、最小字符。
时间: 2023-05-28 10:03:33 浏览: 116
string = input("请输入字符串:")
# 将字符串按空白字符分割成子串并存储到列表中
substrings = string.split()
# 初始化最长子串、最短子串、最大字符、最小字符
longest_sub = shortest_sub = substrings[0]
max_char = min_char = substrings[0][0]
# 循环遍历所有子串
for substr in substrings:
# 更新最长子串、最短子串
if len(substr) > len(longest_sub):
longest_sub = substr
elif len(substr) < len(shortest_sub):
shortest_sub = substr
# 更新最大字符、最小字符
if max(substr) > max_char:
max_char = max(substr)
if min(substr) < min_char:
min_char = min(substr)
print("最长子串:", longest_sub)
print("最短子串:", shortest_sub)
print("最大字符:", max_char)
print("最小字符:", min_char)
相关问题
用python实现,输入一字符串,各个子串之间按空白字符隔开,分别显示其中最长、最短子串,以及最大、最小字符。
```python
s = input("请输入字符串:")
substrings = s.split() # 利用split函数按空白字符将字符串分割成子串列表
# 寻找最长子串和最短子串
longest_substring = shortest_substring = substrings[0] # 先将第一个子串赋值为最长和最短子串
for i in range(1, len(substrings)):
if len(substrings[i]) > len(longest_substring):
longest_substring = substrings[i]
if len(substrings[i]) < len(shortest_substring):
shortest_substring = substrings[i]
# 寻找最大字符和最小字符
max_char = min_char = s[0] # 先将第一个字符赋值为最大和最小字符
for i in range(1, len(s)):
if s[i] > max_char:
max_char = s[i]
if s[i] < min_char:
min_char = s[i]
print("最长子串:", longest_substring)
print("最短子串:", shortest_substring)
print("最大字符:", max_char)
print("最小字符:", min_char)
```
示例输出:
```
请输入字符串:hello world Python
最长子串: Python
最短子串: hello
最大字符: y
最小字符:
```
代码实现python1.输入一字符串,各个子串之间按空白字符隔开,分别显式其中最长、最短子串,以及最大、最小字符。
string = input("请输入一字符串:")
substr_list = string.split() # 以空白字符为分隔符,获取所有子串
max_substr = max(substr_list, key=len) # 获取最长子串
min_substr = min(substr_list, key=len) # 获取最短子串
all_chars = ''.join(substr_list) # 将所有子串合并
max_char = max(all_chars) # 获取最大字符
min_char = min(all_chars) # 获取最小字符
print("最长子串为:", max_substr)
print("最短子串为:", min_substr)
print("最大字符为:", max_char)
print("最小字符为:", min_char)
阅读全文