Itzik984
Itzik984

Reputation: 16764

Extract value from string in Python?

I want to handle 2 cases:

  1. (string) -> string

  2. @string otherStuff -> string

how can it be done?

Upvotes: 0

Views: 433

Answers (3)

Levon
Levon

Reputation: 143017

Will this work for you?

In [45]: s='(string)' 
In [46]: s = s[1:-1]

In [47]: s
Out[47]: 'string'

and

In [48]: s = '@string otherstuff'
In [49]: s=' '.join(s.split()[1:])  

In [50]: s
Out[51]: 'otherstuff'

Upvotes: 0

Niall Byrne
Niall Byrne

Reputation: 2460

import re

def getstring(string):
    testforstring = re.search("\((.*)\)",string)
    if testforstring:
        return testforstring.group(1)
    testforstring = re.search("@(.*?)\s+.*",string)
    if testforstring:
        return testforstring.group(1)
    return None

Allows you to do:

>>> print getstring('(hello)')
hello
>>> print getstring('@hello sdfdsf')
hello

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '(string)').groups()
('string', None)
>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '@string otherStuff').groups()
(None, 'string')

Upvotes: 2

Related Questions