Python - get string between parantheses - python

Example (suppose this is a string):
0.1+0.5*(sign(t-0.5)+1)*t + sign(t+0.8)
I have to get the string 't-0.5' and 't+0.8' between the parantheses of the sign functions (=string in this case), so that after substitution I can get for example:
0.1+0.5*(copysign(1,t-0.5)+1)*t + copysign(1,t+0.8)
Any help would be appreciated.

Your question is not very clear, but if you want a solution for this specific case, then here it is:
>>> s = '0.1+0.5*(sign(t-0.5)+1)*t + sign(t+0.8)'
>>> s.replace('sign(', 'copysign(1,')
'0.1+0.5*(copysign(1,t-0.5)+1)*t + copysign(1,t+0.8)'
If you want a more general replacement, it could be quite tricky.

You can use regex:
>>> import re
>>> s = '0.1+0.5*(sign(t-0.5)+1)*t + sign(t+0.8)'
>>> print re.sub(r'sign\((t.*?)\)', r'copysign(1,\1)', s)
0.1+0.5*(copysign(1,t-0.5)+1)*t + copysign(1,t+0.8)
Someone could probably come up with a better expression; I'm not that great at regex. But it works :).

Related

Better way to change specific chars in a string separated by underscores without using re

I have files with names like centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg. I want to change the last string i.e. image_name.split('_')[5].split('.')[0] to some other string. I can't seem to find a neat way to do this and ended up doing the following which is very crude
new_name = image_base.split('_')[0] + image_base.split('_')[1] + image_base.split('_')[2] + image_base.split('_')[3] + image_base.split('_')[4] + frameNumber
That is, my output should be centerOne_camera_2_2018-04-11_15:11:21_<some string>.0.jpg
Any better way is appreciated. Note: I want to retain the rest of the string too.
I think you may be looking for this:
>>> "centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg".rpartition("_")
('centerOne_camera_2_2018-04-11_15:11:21', '_', '2.0.jpg')
That is for the last element. But from the comments I gather you want to split at delimiter n.
>>> n = 3
>>> temp = "centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg".split("_",n)
>>> "_".join(temp[:n]),temp[n]
('centerOne_camera_2', '2018-04-11_15:11:21_2.0.jpg')
I'm not sure what your objection to using + is, but you can do this if you like:
>>> temp="centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg".rpartition("_")
>>> "{0}<some_string>{2}".format(*temp)
'centerOne_camera_2_2018-04-11_15:11:21<some_string>2.0.jpg'
You can try rsplit:
"centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg".rsplit("_", 1)
['centerOne_camera_2_2018-04-11_15:11:21', '2.0.jpg']

Complex regex in Python

I am trying to write a generic pattern using regex so that it fetches only particular things from the string. Let's say we have strings like GigabitEthernet0/0/0/0 or FastEthernet0/4 or Ethernet0/0.222. The regex should fetch the first 2 characters and all the numerals. Therefore, the fetched result should be something like Gi0000 or Fa04 or Et00222 depending on the above cases.
x = 'GigabitEthernet0/0/0/2
m = re.search('([\w+]{2}?)[\\\.(\d+)]{0,}',x)
I am not able to understand how shall I write the regular expression. The values can be fetched in the form of a list also. I write few more patterns but it isn't helping.
In regex, you may use re.findall function.
>>> import re
>>> s = 'GigabitEthernet0/0/0/0 '
>>> s[:2]+''.join(re.findall(r'\d', s))
'Gi0000'
OR
>>> ''.join(re.findall(r'^..|\d', s))
'Gi0000'
>>> ''.join(re.findall(r'^..|\d', 'Ethernet0/0.222'))
'Et00222'
OR
>>> s = 'GigabitEthernet0/0/0/0 '
>>> s[:2]+''.join([i for i in s if i.isdigit()])
'Gi0000'
z="Ethernet0/0.222."
print z[:2]+"".join(re.findall(r"(\d+)(?=[\d\W]*$)",z))
You can try this.This will make sure only digits from end come into play .
Here is another option:
s = 'Ethernet0/0.222'
"".join(re.findall('^\w{2}|[\d]+', s))

python regular expression with re.split()

i have this string equation:
400-IF(3>5,5,5)+34+IF(4>5,5,6)
i want to split it by string 'IF(3>5,5,5)', means 'IF()' syntax, so here i used two if syntax.
so re.split() should give list with length: 2 ['400-', '+34+']
I made re and used as below.
re.split('IF[\(][0-9,a-z,A-Z,\$]*[\>|\<|=|/|%|*|^]?(.*)+[\,][0-9,a-z,A-Z,\$]*[\,][0-9,a-z,A-Z,\$]+[\)]', '400-IF(3>5,5,5)+34+IF(4>5,5,6)
')
But it is not returning proper answer. What is the mistake in my re. I am new in re.
Can anyone modify this re in python?
x="400-IF(3>5,5,5)+34+IF(4>5,5,6)"
print [i for i in re.split(r"IF\([^)]*\)",x) if i]
You can simply use this.
>>> z = '400-IF(3>5,5,5)+34+IF(4>5,5,6)'
>>> ' '.join(re.split(r'IF\(.*?\)',z)).split()
['400-', '+34+']

regex and replace on string using python

I am rather new to Python Regex (regex in general) and I have been encountering a problem. So, I have a few strings like so:
str1 = r'''hfo/gfbi/mytag=a_17014b_82c'''
str2 = r'''/bkyhi/oiukj/game/?mytag=a_17014b_82c&'''
str3 = r'''lkjsd/image/game/mytag=a_17014b_82c$'''
the & and the $ could be any symbol.
I would like to have a single regex (and replace) which replaces:
mytag=a_17014b_82c
to:
mytag=myvalue
from any of the above 3 strings. Would appreciate any guidance on how I can achieve this.
UPDATE: the string to be replaced is always not the same. So, a_17014b_82c could be anything in reality.
If the string to be replaced is constant you don't need a regex. Simply use replace:
>>> str1 = r'''hfo/gfbi/mytag=a_17014b_82c'''
>>> str1.replace('a_17014b_82c','myvalue')
'hfo/gfbi/mytag=myvalue'
Use re.sub:
>>> import re
>>> r = re.compile(r'(mytag=)(\w+)')
>>> r.sub(r'\1myvalue', str1)
'hfo/gfbi/mytag=myvalue'
>>> r.sub(r'\1myvalue', str2)
'/bkyhi/oiukj/game/?mytag=myvalue&'
>>> r.sub(r'\1myvalue', str3)
'lkjsd/image/game/mytag=myvalue$'
import re
r = re.compile(r'(mytag=)\w+$')
r.sub(r'\1myvalue', str1)
This is based on #Ashwini's answer, two small changes are we are saying the mytag=a_17014b part should be at the end of input, so that even inputs such as
str1 = r'''/bkyhi/mytag=blah/game/?mytag=a_17014b_82c&'''
will work fine, substituting the last mytag instead of the the first.
Another small change is we are not unnecessarily capturing the \w+, since we aren't using it anyway. This is just for a bit of code clarity.

Python regular words cut

I have string: './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
I need string: '27-10-2011 17:07:02'
How can i do this in python?
There are many ways to do this, one way is to use str.partition:
text='./money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
before,_,after = text.partition('[')
print(after[:-1])
# 27-10-2011 17:07:02
Another is to use str.split:
before,after = text.split('[',1)
print(after[:-1])
# 27-10-2011 17:07:02
or str.find and str.rfind:
ind1 = text.find('[')+1
ind2 = text.rfind(']')
print(text[ind1:ind2])
All these methods rely on the desired substring immediately following the first left-bracket [.
The first two methods also rely on the desired substring ending at the next-to-last character in text. The last method (using rfind) searches from the right for the index of the right-bracket, so it is a little more general, and does not depend on quite so many (potential off-by-one) constants.
If your string has always the same structure this is probably the simplest solution:
s = r'./money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
s[s.find("[")+1:s.find("]")]
Update:
After seeing some of the other answers this is a slight improvement:
s[s.find("[")+1:-1]
Exploiting the fact that the closing square bracket is the last character in your string.
If the format is "fixed", you can also use this
>>> s = './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
>>> s[-20:-1:]
'27-10-2011 17:07:02'
>>>
You can also use regular expression:
import re
s = './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
print re.search(r'\[(.*?)\]', s).group(1)
Try with a regex :
import re
re.findall(".*\[(.*)\]", './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]')
>>> ['27-10-2011 17:07:02']
Probably the easiest way(if you know the string will always be in this format
>>> s = './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
>>> s[s.index('[') + 1:-1]
'27-10-2011 17:07:02'

Categories

Resources