Alex
Alex

Reputation: 625

How to remove characters from a str in python?

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?

Upvotes: 1

Views: 184

Answers (4)

tegancp
tegancp

Reputation: 1202

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]

Upvotes: 2

lmiguelvargasf
lmiguelvargasf

Reputation: 69983

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

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522732

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

Upvotes: 1

gmds
gmds

Reputation: 19895

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

Upvotes: 1

Related Questions