从键盘读入若干个字符串,对它们按字母大小的顺序排序,然后把排好序的字符串
时间: 2024-06-14 18:05:05 浏览: 14
以下是从键盘读入若干个字符串,对它们按字母大小的顺序排序,并输出排好序的字符串的示例代码:
```python
n = int(input("请输入字符串的个数:"))
strings = []
for i in range(n):
string = input("请输入第{}个字符串:".format(i+1))
strings.append(string)
sorted_strings = sorted(strings)
print("排好序的字符串为:")
for string in sorted_strings:
print(string)
```
相关问题
从键盘读入若干个字符串,对它们按字母大小的顺序排序,然后把排好序的字符串送到磁盘文件中保存。
以下是从键盘读入若干个字符串,对它们按字母大小的顺序排序,然后把排好序的字符串送到磁盘文件中保存的示例代码:
```python
# 从键盘读入若干个字符串
n = int(input("请输入字符串的个数:"))
strings = []
for i in range(n):
string = input("请输入第{}个字符串:".format(i+1))
strings.append(string)
# 对字符串按字母大小的顺序排序
strings.sort()
# 将排好序的字符串保存到磁盘文件中
with open("test.txt", "w") as file:
for string in strings:
file.write(string + "\n")
```
请注意,上述代码中的`test.txt`是保存排好序的字符串的文件名,你可以根据需要修改文件名。
从键盘读入若干个字符串,对它们按字母大小的顺序排序,然后把排好序的字符串送到磁盘文件中保存
可以使用Python的内置函数sorted()对字符串列表进行排序,然后使用文件操作将排序后的字符串写入磁盘文件中。下面是一个示例代码:
```python
# 从键盘读入若干个字符串
strings = []
while True:
string = input("请输入字符串(输入空字符串结束):")
if string == "":
break
strings.append(string)
# 对字符串列表进行排序
sorted_strings = sorted(strings)
# 将排序后的字符串写入磁盘文件
with open("sorted_strings.txt", "w") as file:
for string in sorted_strings:
file.write(string + "\n")
```
这段代码首先使用一个循环从键盘读入若干个字符串,直到输入空字符串为止。然后使用sorted()函数对字符串列表进行排序,将排序结果保存在sorted_strings变量中。最后,使用with语句打开一个文件,并将排序后的字符串逐行写入文件中。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)