Home > Blockchain >  how to find value in (txt) python string
how to find value in (txt) python string

Time:09-22

i'm new to python world and i'm trying to extract value from text. I try to find the keyword by re.search('keyword') , but I want to get the value after keyword

text = word1:1434, word2:4446, word3:7171

i just want to get the value of word1

i try

keyword = 'word1'
before_keyword, keyword, after_keyword = text.partition(keyword)
print(after_keyword)

output

:1434, word2:4446, word3:7171

i just want to get the value of word1 (1434)

CodePudding user response:

Here is how you can search the text using regular expressions:

import re

keyword_regex = r'word1:(\d )'
text = "word1:1434, word2:4446, word3:7171"
keyword_value = re.search(keyword_regex, text)
print(keyword_value.group(1))

The RegEx word1:(\d ) searches for the string word1: followed by one or more digits. It stops matching when the next character is not a digit. The parentheses around (\d ) make this part a capturing group which is what enables you to access it later using keyword_value.group(1).

More about regular expressions here and Python's re module here.

CodePudding user response:

Assuming Text input is a string not dict; then

text = "word1:1434, word2:4446, word3:7171"
keyword = 'word1'
print(text.split(keyword ":")[1].split(",")[0])

Hope this helps...

CodePudding user response:

You could use Dictionary data type to simplify this, here's how you could do that:

text = {
    'word1':1434,
    'word2':4446,
    'word3':7171
}

name = 'word1'

if name in text.keys():
    print(text.get(name))
  • Related