-4

Hi I guess that the title says it all.

For example if I have a string like: "The food! is great!!!"

I want python to change it to: "The food is great!"

Thank you all in advance. :)

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
melindaou
  • 29
  • 1
  • 5

3 Answers3

4

You can use a regex with lookahead:

import re

re.sub(r'!+(?=.*\!)','',text)

The regex

!+(?=.*\!)

matches any sequences of exclamation marks given the lookahead (?=.*\!) sees an exclamation mark. All these exclamation marks are substituted by the empty string.

$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> text="The food! is great!!!"
>>> re.sub(r'!+(?=.*\!)','',text)
'The food is great!'
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 2
    i think this is a bit too advanced for the OP and anyone who would lookup such a thing – Ma0 Jan 25 '17 at 17:32
  • advanced yes, but it is a valid solution – depperm Jan 25 '17 at 17:34
  • 3
    @Ev.Kounis: well personally I think regexes are very elegant tools because you *specify* what you want and do not have to worry (much) about how it works behind the curtains. Furthermore that's in my opinion not a reason for a dv: it is functionally correct and the answer explains what is happening. – Willem Van Onsem Jan 25 '17 at 17:34
  • Furthermore if later the OP changes their mind and wants to tweak the specifications a bit, he/she should probably not return to this site for another question. Regexes are a common tool and there is plenty of documentation on it. – Willem Van Onsem Jan 25 '17 at 17:37
  • I did not downvote and i find the answer a very fine one. Putting my self in OP's shoes though, I probably wouldn't even read it in fear of its complexity. – Ma0 Jan 25 '17 at 17:38
2
strs="The food! is great!!!"
count=strs.count("!")-1
strs = strs.replace('!','',count)
print strs

https://stackoverflow.com/a/16268024/6626530

output

The food is great!
Community
  • 1
  • 1
Shijo
  • 9,313
  • 3
  • 19
  • 31
-2

replace all '!' in the string with ''. then string = string + '!'

string.replace('!','')
string = string + '!'
techkris
  • 5
  • 3