编程序输入一个字符串,包含空格、数字、字母,将字符串保存到文件a1.txt中。从a.txt中读入内容,将其中的空格、数字去掉,并将结果保存到b.txt中。输入若干行字符串,包含空格、数字、字母,将字符串保存到文件a2.txt中,当输入-1时结束。从a2.txt中读入内容,将每一行的空格、数字去掉,python并将结果保存到b.txt中。
时间: 2023-11-22 17:53:55 浏览: 45
以下是Python的代码实现:
```python
# 将字符串保存到a1.txt中
string = input("请输入一个字符串:")
with open("a1.txt", "w") as f:
f.write(string)
# 从a1.txt中读取内容,去掉空格和数字,并保存到b.txt中
with open("a1.txt", "r") as f1, open("b.txt", "w") as f2:
for line in f1:
new_line = ''.join([c for c in line if c.isalpha()])
f2.write(new_line)
# 将多行字符串保存到a2.txt中
strings = []
while True:
string = input("请输入一个字符串:")
if string == "-1":
break
strings.append(string)
with open("a2.txt", "w") as f:
f.write('\n'.join(strings))
# 从a2.txt中读取内容,去掉空格和数字,并保存到b.txt中
with open("a2.txt", "r") as f1, open("b.txt", "w") as f2:
for line in f1:
new_line = ''.join([c for c in line if c.isalpha()])
f2.write(new_line)
```
以上代码中,使用了Python内置的字符串函数isalpha()来判断一个字符是否为字母。同时,使用了列表推导式来把字符串中的非字母字符去掉。在保存多行字符串时,使用了一个while循环来不断输入字符串,直到输入了-1为止。最后,使用了文件读写操作中with语句的上下文管理器来自动关闭文件。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)