Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be using regex in Python

Tags:

python

regex

I have a string like so:

'cathy is a singer on fridays'

and I want to be able to replace the fourth word with other verbs

so

'cathy is a dancer on fridays'

I assumed the right way to do this would be to use regex and stop when you reach the third whitespace but you can do groupings with regex and * which accepts any char. I can't seem to get it working.

Any advice would be useful. I am new to Python so please dont judge.Also is regex appropriate for this or should I use another method?

Thank you

like image 706
user2897415 Avatar asked Sep 08 '26 07:09

user2897415


1 Answers

No, Regex is not needed for this. See below:

>>> mystr = 'cathy is a singer on fridays'
>>> x = mystr.split()
>>> x
['cathy', 'is', 'a', 'singer', 'on', 'fridays']
>>> x[3] = "dancer"
>>> x
['cathy', 'is', 'a', 'dancer', 'on', 'fridays']
>>> " ".join(x)
'cathy is a dancer on fridays'

Or, more compact:

>>> mystr = 'cathy is a singer on fridays'
>>> x = mystr.split()
>>> " ".join(x[:3] + ["dancer"] + x[4:])
'cathy is a dancer on fridays'
>>>

The core principle here is the .split method of a string.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!