string formatting

Asked

Viewed 257 times

2

I have the following string:

JOSÉ CARLOS ALMEIDA         (0-2) 1

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

this way I can deal with the trim, split etc...

but this my string will not always be the same as sometimes can come:

JOSÉ SAMUEL         (0-2) 1

and or

CARLOS MANGUEIRA        (0-2) 1

how can I treat these variations?

  • will always come (0-2) 1 at the end? or may vary type (10-25) 1

  • Daniel, may vary yes

2 answers

5


Mount a substring with the initial index at the opening of the parentheses and that goes all the way to the end.

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

Upshot:

(0-2) 1

Works independent of the number of digits within the parentheses.

4

You can also do it with regular expressions, considering that the pattern is always the same:

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

Where número would be any sequence of digits (i.e. non-negative integers), the regex would be:

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

Extracting content from 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 exit is:

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

See working on Repl.it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.