Home > Enterprise >  How to extract text between specific letters from a string in Python(3.9)?
How to extract text between specific letters from a string in Python(3.9)?

Time:11-04

how may I be able to take from a string in python a value that is in a given text but is inside it, it's between 2 letters that I want it to copy from inside. e.g.

"Kahoot : ID:1234567 Name:RandomUSERNAME"

I want it to receive the 1234567 and the RandomUSERNAME in 2 different variables. a way I found to catch is to get it between the "ID:"COPYINPUT until the SPACE., "Name:"COPYINPUT until the end of the text.

How do I code this?

if I hadn't explained correctly tell me, I don't know how to ask/format this question! Sorry for any inconvenience!.

CodePudding user response:

If the text always follows the same format you could just split the string. Alternatively, you could use regular expressions using the re library.

Using split:

string = "Kahoot : ID:1234567 Name:RandomUSERNAME"

string = string.split(" ")

id = string[2][3:]
name = string[3][5:]

print(id)
print(name)

Using re:

import re

string = "Kahoot : ID:1234567 Name:RandomUSERNAME"

id = re.search(r'(?<=ID:).*?(?=\s)', string).group(0)
name = re.search(r'(?<=Name:).*', string).group(0)

print(id)
print(name)
  • Related