1

I have the following str I want to delete characters.

For example:

from str1 = "A.B.1912/2013(H-0)02322" to 1912/2013

from srt2 = "I.M.1591/2017(I-299)17529" to 1591/2017

from str3 = "I.M.C.15/2017(I-112)17529" to 15/2017

I'm trying this way, but I need to remove the rest from ( to the right

newStr = str1.strip('A.B.')

'1912/2013(H-0)02322'

For the moment I'm doing it with slice notation

str1 = "A.B.1912/2013(H-0)02322"

str1 = str1[4:13]

'1912/2013'

But not all have the same length.

Any ideas or suggestions?

1
  • str1.split('(')[0] as a starter. Commented Apr 2, 2019 at 4:49

4 Answers 4

2

With some (modest) assumptions about the format of the strings, here's a solution without using regex:

First split the string on the ( character, keeping the substring on the left:

left = str1.split( '(' )[0]   # "A.B.1912/2013"

Then, split the result on the last . (i.e. split from the right just once), keeping the second component:

cut = left.rsplit('.', 1)[1]  # "1912/2013"

or combining the two steps into a function:

def extract(s):
    return s.split('(')[0].rsplit('.', 1)[1]
Sign up to request clarification or add additional context in comments.

Comments

1

Use a regex instead:

import re

regex = re.compile(r'\d+/\d+')

print(regex.search(str1).group())
print(regex.search(str2).group())
print(regex.search(str3).group())

Output:

1912/2013
1591/2017
15/2017

Comments

1

We can try using re.sub here with a capture group:

str1 = "A.B.1912/2013(H-0)02322"
output = re.sub(r'.*\b(\d+/\d+)\b.*', '\\1', str1)
print(output)

1912/2013

Comments

1

You have to use a regular expression to solve this problem.

import re

pattern = r'\d+/\d+'

str1 = "A.B.1912/2013(H-0)02322"
srt2 = "I.M.1591/2017(I-299)17529"
str3 = "I.M.C.15/2017(I-112)17529"

print(*re.findall(pattern, str1))
print(*re.findall(pattern, str2))
print(*re.findall(pattern, str3))

Output:

1912/2013
1591/2017
15/2017

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.