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)
this is my code so far. it is printing the string before the other string, but i would like it to print whatever is contained in the string "word" ONLY at its first occurence (if the word has been repeated 3 times). How do I do so?
If I understood you correctly, you want the following: If a word occurs 3 times in a string input, you want to keep the first occurrence and delete all the following occurrences.
To do that, you need to split para
on the first occurrence of word
. You can do that the following way:
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)
I am also not sure what kind of output you would expect. An example user input and desired output would be helpful.
Since you are already using re, have you considered this: re.sub(word, "", para)
Also note the difference in replacement strings: " " or "". " " means you will be adding whitespaces into your paragraph.
"
This is an example paragraph, to serve as an example to this example."
Would result in:
"This is an example paragraph, to serve as an to this."
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.