1、从键盘输入 10个字符串,至少有两个字符串中含有“the”, 每个字符串不超过100个字符,建立一个文本文件wenjian.txt,每个字符串占一-行。
时间: 2023-11-28 12:50:06 浏览: 28
以下是Python代码实现:
```python
# 从键盘输入10个字符串
strings = []
count = 0
while count < 10:
string = input("请输入第%d个字符串:" % (count + 1))
if "the" in string:
strings.append(string)
count += 1
else:
print("该字符串不符合要求,请重新输入。")
# 将字符串写入文本文件wenjian.txt中
with open("wenjian.txt", "w") as file:
for string in strings:
file.write(string + "\n")
```
以上代码中,我们利用一个 while 循环从键盘输入 10 个字符串,并且要求每个字符串中必须含有单词“the”,否则需要重新输入。如果符合要求,则将字符串存储到列表 strings 中。最后,我们使用 with 语句打开文件 wenjian.txt 并依次将字符串写入文件中。注意,每个字符串占一行,因此需要在字符串末尾添加换行符“\n”。
相关问题
从键盘输入 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",则会提示用户重新输入。
python从键盘输入 10个字符串,至少有两个字符串中含有“the”, 每个字符串不超过100个字符,建立一个文本文件wenjian.txt,每个字符串占-行。
可以使用以下代码实现:
```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”为止。然后将这些字符串写入文本文件,每个字符串占一行。