string formatting

2

I have the following string:

JOSÉ CARLOS ALMEIDA         (0-2) 1

I need to remove the text and spaces and leave (0-2) 1

This way I can deal with trim , split etc ...

But my string will not always be the same as the times can come:

JOSÉ SAMUEL         (0-2) 1

and or

CARLOS MANGUEIRA        (0-2) 1

How can I handle these variations?

    
asked by anonymous 13.03.2017 / 18:37

2 answers

5

Assemble a substring with the opening index in the opening parentheses and that goes all the way.

str = 'CARLOS MANGUEIRA        (0-2) 1'  # string de exemplo
index = str.find('(')  # indice comecando na abertura de parenteses
substr = str[index:]  # substring que vai do indice até o fim da string de exemplo
print substr

Result:

  

(0-2) 1

It works regardless of the number of digits inside the parentheses.

    
13.03.2017 / 18:47
4

You can also do with regular expressions, assuming the pattern is always the same:

(número-número) número

Where número would be any sequence of digits (i.e. nonnegative integers), regex would look like:

\(\d+\-\d+\)\s\d+

Extracting the contents of the strings:

import re

values = [
  "JOSÉ CARLOS ALMEIDA         (0-2) 1",
  "JOSÉ SAMUEL         (3-4) 7",
  "CARLOS MANGUEIRA        (2-10) 99"
]

for value in values:
  result = re.search(r"\(\d+\-\d+\)\s\d+", value)
  if result:
    print(result.group(0))

The output is:

(0-2) 1
(3-4) 7
(2-10) 99

See working at Repl.it .

    
13.03.2017 / 18:58