代码实现python1.输入一字符串,各个子串之间按空白字符隔开,分别显式其中最长、最短子串,以及最大、最小字符。
时间: 2023-05-26 14:05:30 浏览: 92
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)
相关问题
编写函数实现python1.输入一字符串,各个子串之间按空白字符隔开,分别显式其中最长、最短子串,以及最大、最小字符。 点击复制后,将打开C知道体验页
def string_analysis(string):
substrings = string.split() # 将字符串按空白字符分隔成子串
max_len = 0
min_len = len(string)
max_char = ''
min_char = '~' # ASCII码表中~是最小字符可打印字符
for substring in substrings:
if len(substring) > max_len:
max_len = len(substring)
max_substring = substring
if len(substring) < min_len:
min_len = len(substring)
min_substring = substring
for char in substring:
if char > max_char:
max_char = char
if char < min_char:
min_char = char
print("最长子串:", max_substring)
print("最短子串:", min_substring)
print("最大字符:", max_char)
print("最小字符:", min_char)
# 测试
string_analysis("hello world hi")
# 输出:
# 最长子串: world
# 最短子串: hi
# 最大字符: w
# 最小字符:
代码实现:python-输入一字符串,各个子串之间按空白字符隔开,分别显式其中最长、最短子串,以及最大、最小字符。
str = input("请输入字符串:")
sub_str = str.split() # 按空白字符分割字符串,得到子串列表
max_len = 0
min_len = len(sub_str[0])
max_char = sub_str[0][0]
min_char = sub_str[0][0]
for s in sub_str:
if len(s) > max_len:
max_len = len(s)
max_sub = s
if len(s) < min_len:
min_len = len(s)
min_sub = s
if max(s) > max_char:
max_char = max(s)
if min(s) < min_char:
min_char = min(s)
print("最长子串:", max_sub)
print("最短子串:", min_sub)
print("最大字符:", max_char)
print("最小字符:", min_char)
阅读全文