![](/img/trans.png)
[英]How do I print a specific message if the user inputs the same string twice in Python?
[英]How do I print a string into a string in a specific location depending on user input?
import re
print ("enter a long paragraph.")
para=input()
print ("what word would you like to key search?")
word=input()
count = para.count(word)
print (count)
if count == 3:
para=para.replace(word," ")
print (para)
final=word+para
print (final)
到目前为止,这是我的代码。 它在另一个字符串之前打印字符串,但我希望它仅在第一次出现时打印字符串“word”中包含的任何内容(如果该词已重复 3 次)。 我该怎么做?
如果我理解正确,您需要以下内容:如果一个单词在字符串输入中出现 3 次,您希望保留第一次出现并删除所有以下出现。
为此,您需要在第一次出现word
时拆分para
。 您可以通过以下方式执行此操作:
import re
print ("enter a long paragraph.")
para=input()
print ("what word would you like to key search?")
word=input()
count = para.count(word)
print (count)
if count == 3:
before_word = para.split(word)[0]
after_word= para.split(word, 1)[1]
print(before_word+after_word)
我也不确定你会期待什么样的 output。 示例用户输入和所需的 output 会有所帮助。
既然你已经在使用 re,你有没有考虑过这个: re.sub(word, "", para)
还要注意替换字符串的区别:“”或“”。 " " 表示您将在段落中添加空格。
“
This is an example paragraph, to serve as an example to this example."
会导致:
"This is an example paragraph, to serve as an to this."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.