python编写程序,创建 test.txt 文件,将字符串 str = ‘Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul. 分成 2 行写入 test.txt
时间: 2024-03-26 21:42:01 浏览: 13
好的,以下是 Python 编写的程序,创建 `test.txt` 文件,并将字符串 `str` 分成 2 行写入 `test.txt`:
```python
str = 'Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul.'
# 将字符串按空格分割成单词列表
words = str.split()
# 计算单词列表的长度
len_words = len(words)
# 计算每行应该写入的单词数量
len_line = len_words // 2
# 将单词列表分成两个子列表
words1 = words[:len_line]
words2 = words[len_line:]
# 将子列表转换成字符串
line1 = ' '.join(words1)
line2 = ' '.join(words2)
# 创建 test.txt 文件并写入两行字符串
with open('test.txt', 'w') as f:
f.write(line1 + '\n')
f.write(line2 + '\n')
```
程序首先将字符串 `str` 按空格分割成单词列表 `words`,然后计算单词列表的长度 `len_words`。接下来计算每行应该写入的单词数量 `len_line`,这里采用整除运算符 `//` 来保证结果为整数。
将单词列表分成两个子列表 `words1` 和 `words2`,分别包含前一半和后一半的单词。然后将子列表转换成字符串 `line1` 和 `line2`,每个子列表中的单词之间用空格连接。
最后,程序创建 `test.txt` 文件并写入两行字符串,每行字符串末尾加上换行符 `\n`。可以使用文本编辑器打开 `test.txt` 文件,查看其中的内容。