python从键盘输入 10个字符串,至少有两个字符串中含有“the”, 每个字符串不超过100个字符,建立一个文本文件wenjian.txt,每个字符串占一行。
时间: 2023-12-14 16:38:45 浏览: 33
以下是实现该功能的Python代码:
```python
# 从键盘输入10个字符串
strings = []
count = 0
while count < 10:
s = input("请输入第{}个字符串:".format(count+1))
if "the" in s:
count += 1
strings.append(s)
# 将字符串写入文本文件
with open("wenjian.txt", "w") as f:
for s in strings:
f.write(s + "\n")
```
首先,我们使用一个循环从键盘中读取10个字符串,如果有字符串中包含“the”,就将其加入到一个列表中。读取完毕后,我们使用文件操作将这些字符串写入到名为“wenjian.txt”的文本文件中,每个字符串占一行。
相关问题
用python从键盘输入 10个字符串,至少有两个字符串中含有“the”, 每个字符串不超过100个字符,建立一个文本文件wenjian.txt,每个字符串占一-行。
可以使用以下代码实现:
```python
# 输入10个字符串
strings = []
count = 0
while count < 10:
s = input(f"请输入第{count+1}个字符串:")
if "the" in s:
strings.append(s)
count += 1
else:
print("该字符串不含有'the',请重新输入。")
# 将字符串写入文件
with open("wenjian.txt", "w") as f:
for s in strings:
f.write(s + "\n")
```
首先通过一个循环,从键盘输入10个字符串,并将包含“the”的字符串添加到列表中。如果某个字符串不含有“the”,则会提示重新输入。
接着,使用`with open()`语句打开文件并将每个字符串写入文件中,每个字符串占一行。最后,文件会保存在当前工作目录下的`wenjian.txt`文件中。
从键盘输入 10个字符串,至少有两个字符串中含有“the”, 每个字符串不超过100个字符,建立一个文本文件wenjian.txt,每个字符串占一行。
以下是一个 Python 代码示例,实现了从键盘输入10个字符串,筛选出含有"the"的字符串并写入文本文件wenjian.txt中。
```python
# 打开文本文件
with open("wenjian.txt", "w") as f:
count = 0
while count < 10:
# 从键盘读入字符串
s = input("请输入第{}个字符串:".format(count+1))
# 判断字符串中是否含有"the"
if "the" in s:
# 写入文本文件
f.write(s + "\n")
count += 1
else:
print("输入的字符串不含有'the',请重新输入。")
print("写入完成。")
```
运行程序后,会提示用户输入10个字符串,如果有含有"the"的字符串,则会写入到文本文件wenjian.txt中,每个字符串占一行。如果输入的字符串不含有"the",则会提示用户重新输入。