Home > Mobile >  Select a particular word from string in python
Select a particular word from string in python

Time:12-08

I have a string that goes like this

string = '12345_1234567890_1_someword_someword2'

I want to choose the very first non numerical char string that appears In this given example, I want to select 'someword'. The structure of sting is fixed. A sequence of numbers then some characters.

CodePudding user response:

string = input('')
stringArr = string.split('_')

for item in stringArr:
    try:
       item = int(item)
    except ValueError:
        print(item)
        break

This code splits the string based off underscores, then tries to convert each item into an integer. If one can not, then it prints them item. (You can also save the item under the exception to a variable or whatever you like)

This might be a bit more efficient than regex, as this stops after the first occurrence, instead of finding all occurrences

CodePudding user response:

import re
string = '_'   '12345_1234567890_1_someword_someword2'   '_'
re.findall('_([a-zA-Z] ?)_',string)[0]

Alternatively:

string = '12345_1234567890_1_someword_someword2'
pattern = '(^|_)([a-zA-Z] ?)(_|$)'
re.search(pattern,string).group(2)

CodePudding user response:

You can use regular expressions:

import re
string = '12345_1234567890_1_someword_someword2'
m = re.search("([a-zA-Z] )", string)
m.group(0)

will return 'someword'.

CodePudding user response:

Use only a simple split function. for extracting String part

string.split('_')[-2:]

Or if you are familiar with regex so you can use that as well.

  • Related