Home > OS >  How to get specific text from a string?
How to get specific text from a string?

Time:01-05

The string below is what I receive as output and I specifically want the numbers within the square brackets.

4 requests to https://twitter.com/search?f=live&lang=en&q=from:Username&src=spelling_expansion_revert_click failed, giving up.
[3962342629375400258]

I have attempted split(), but is there an efficient way of extracting it?

CodePudding user response:

In the case that your number in brackets is always on a separate line without any other prefixes or suffixes except the square brackets and an optional trailing new line, I would use:

s = '...\n[1234]'
s.rstrip().rsplit(sep='\n', maxsplit=1)[-1].removeprefix('[').removesuffix(']')

First we ensure to remove any trailing whitespace including a trailing new line. Then we separate the string into two parts, but avoid any unnecessary splitting once we have found the last line beginning from the end of the string. Afterwards we select the last line from the list and remove the brackets.

CodePudding user response:

You can simply use find:

s[s.find("[") 1:s.find("]")]

CodePudding user response:

this code does it find the index of the opening bracket and closing one and cuts the string between those 2 indexes and u get the string between the brackets

string[string.index("[") 1:string.index("]")]

accommodating for @geraldmayr's commend you can delete all the brackets before the ones u want to segment with this code:

string = "fjusfausbfhj[sdfsdfsfsf][1231231231]"

string = string.split("[")[len(string.split("["))-1][:-1]

print(string)
  •  Tags:  
  • Related