python从键盘输入 10个字符串,至少有两个字符串中含有“the”, 每个字符串不超过100个字符,建立一个文本文件wenjian.txt,每个字符串占-行。
时间: 2023-12-10 10:41:45 浏览: 13
可以使用以下代码实现:
```python
# 输入10个字符串
strings = []
count = 0
while count < 10:
text = input("请输入第{}个字符串:".format(count+1))
if 'the' in text:
strings.append(text)
count += 1
else:
print("请至少输入两个包含'the'的字符串!")
# 将字符串写入文本文件
with open("wenjian.txt", "w") as f:
for s in strings:
f.write(s + "\n")
```
这段代码会不断要求用户输入字符串,直到至少有两个字符串中含有“the”为止。然后将这些字符串写入文本文件,每个字符串占一行。
相关问题
python从键盘输入 10个字符串,至少有两个字符串中含有“the”, 每个字符串不超过100个字符,建立一个文本文件wenjian.txt,每个字符串占一行。
以下是实现该功能的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`文件中。