将字符串str="monday tuesday wednesday thursday friday saturday sunday"打印,将里面的小写day替换为大写,输入是否替换,每次替换只能替换一个?替换完成打印字符串!用python写
时间: 2024-11-09 07:19:16 浏览: 27
你可以使用Python的字符串操作和循环来实现这个功能。首先,创建一个函数,然后逐个处理每个单词并将小写的“day”替换为大写。以下是具体的代码示例:
```python
def replace_days():
str_input = "monday tuesday wednesday thursday friday saturday sunday"
days_to_replace = ["tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
replaced_str = ""
for word in str_input.split(" "):
if word.lower() == "day":
print(f"是否替换 '{word}' (y/n)?")
user_choice = input().lower()
if user_choice == "y":
while True:
replacement = input("请输入新的大写字母:")
if replacement.isupper():
replaced_str += replacement + " "
break
else:
print("请输入一个大写字母!")
else:
replaced_str += word + " "
else:
replaced_str += word + " "
print("替换后的字符串:")
print(replaced_str)
replace_days()
```
运行上述代码后,它会提示你是否替换每个“day”,如果你选择替换,程序会等待你输入一个大写字母。如果你选择不替换,原样保留。替换完成后,会打印出修改后的字符串。
阅读全文