Take a string snippet between two characters

Asked

Viewed 50 times

-2

I have some information I need that comes in the following format:

<http://informacaoquepreciso.com.br> "rel"="next"

In this case what I need to pick up only the text that is within the < >, is there any function ready to take this kind of information? I was able to do using the replace.

  • 2

    There is no function ready for this. In fact, it may even exist in some third-party library. Certainly not in the standard library. In general, you will always have to use a set of procedures to retrieve the information you want.

  • Thanks Felipe, only for information this information that I am picking up is the pagination return of a request that I am consuming, and to fetch the next page I have to get the url that is inside the <>. if you have any tips.

  • 1

    Trivially, you can do so (assuming the string always has the question format, of course): str[1:str.index('>')].

2 answers

0

If you are sure that this information always comes this way, you can use the split method.

texto = '<http://informacaoquepreciso.com.br> "rel"="next"'
parte_util = texto.split('>')[0][1:]]
#http://informacaoquepreciso.com.br

This method, will divide the string based on the character you pass and returns a list, so using index (first brackets), you can get the part that comes before the '>'. And with string Slice (the second bracket), you retrieve the string without the first character, in the case, the '<'.

-1


You can use a regular expression:

import re

texto = '<http://informacaoquepreciso.com.br> "rel"="next"'

padrao = re.compile('<(.*?)>')
achado = padrao.match(texto)
if achado:
    print(achado.group(1))
    # Imprime http://informacaoquepreciso.com.br

Note that this method will not work if there is a character > in the information you need, for example <http://informacaoquepreciso>.com.br> "rel"="next".

  • Enzo show too much thank you, could explain a little the regular expression ? , I’m still learning. anyway thank you very much.

Browser other questions tagged

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