Using regular expressions - documentation for further reference
import re
text = 'gfgfdAAA1234ZZZuijjk'
m = re.search('AAA(.+?)ZZZ', text)
if m:
found = m.group(1)
# found: 1234
or:
import re
text = 'gfgfdAAA1234ZZZuijjk'
try:
found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
# AAA, ZZZ not found in the original string
found = '' # apply your error handling
# found: 1234
Answer from eumiro on Stack OverflowUsing regular expressions - documentation for further reference
import re
text = 'gfgfdAAA1234ZZZuijjk'
m = re.search('AAA(.+?)ZZZ', text)
if m:
found = m.group(1)
# found: 1234
or:
import re
text = 'gfgfdAAA1234ZZZuijjk'
try:
found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
# AAA, ZZZ not found in the original string
found = '' # apply your error handling
# found: 1234
>>> s = 'gfgfdAAA1234ZZZuijjk'
>>> start = s.find('AAA') + 3
>>> end = s.find('ZZZ', start)
>>> s[start:end]
'1234'
Then you can use regexps with the re module as well, if you want, but that's not necessary in your case.
The simplest way to extract a substring from a string
Python Question - how do I extract a part of a string - Geographic Information Systems Stack Exchange
python - How to extract a part of a string - Stack Overflow
regex - How do I extract a certain part of a string in Python? - Stack Overflow
Hello,
I'm learning python from scratch, and I am trying to figure out how to "extract" a substring from a string. So, for instance, let's say I want to extract the word within the parenthesis for each of these three strings.
'xx(hi)xx' 'abc(there)xyz' 'xx(c)xx'
I know I could use slicing, but this would involve three operations, I think. I'm wondering if there's a sort of pattern I can leverage. How do you guys approach this kind of problem?
Thank you in advance for your help. It is most appreciated!
The code below searches for the first occurence of the ".dwg" string and assigns a new substring (containing characters up to and including that occurence).
text = "Denver.dwg Group Layer\\Denver.dwg Annotation"
ext = ".dwg"
fileNameOnly = text[:text.find(ext) + len(ext)]
print fileNameOnly
This is very basic Python string manipulation. There are loads of quick references which will help you with these most commonly used functions, for example Python Basics, Section 5: Strings.
You should be able to use this string.find method, see my example below.
s = 'Denver.dwg Group Layer/Denver.dwg Annotation"'
# this returns lowest index of first occurence of dwg
# in this case 7
idx = s.find('dwg')
print idx
# take this index and add 3 for 'dwg'
# get desired string
subs = s[:idx+3]
print subs
import re
s = '-1007.88670550662*p**(-1.0) + 67293.8347365694*p**(-0.416543501823503)'
pattern = r'-?\d+\.\d*'
a,_,b,c = re.findall(pattern,s)
print(a, b, c)
Output
('-1007.88670550662', '67293.8347365694', '-0.416543501823503')
s is your test strings and what not, pattern is the regex pattern, we are looking for floats, and once we find them using findall() we assign them back to a,b,c
Note this method works only if your string is in format of what you've given. else you can play with the pattern to match what you want.
Edit like most people stated in the comments if you need to include a + in front of your positive numbers you can use this pattern r'[-+]?\d+\.\d*'
Using the reqular expression
(-?\d+\.?\d*)\*p\*\*\(-1\.0\)\s*\+\s*(-?\d+\.?\d*)\*p\*\*\((-?\d+\.?\d*)\)
We can do
import re
pat = r'(-?\d+\.?\d*)\*p\*\*\(-1\.0\)\s*\+\s*(-?\d+\.?\d*)\*p\*\*\((-?\d+\.?\d*)\)'
regex = re.compile(pat)
print(regex.findall('-1007.88670550662*p**(-1.0) + 67293.8347365694*p**(-0.416543501823503)'))
will print [('-1007.88670550662', '67293.8347365694', '-0.416543501823503')]
Get the reverse index after splitting by ||:
>>> L = ["|| [email protected] || awlkdjawldkjalwdkda", "|| [email protected] || awdadwawdawdawdawd"]
>>> for x in L:
... print x.split('||')[-1].strip()
...
awlkdjawldkjalwdkda
awdadwawdawdawdawd
Firstly, if you know the exact format of strings you may use split() function. For example
>>> string1 = "1 || [email protected] || awlkdjawldkjalwdkda"
>>> list1 = string1.split("||")
>>> list1
['1 ', ' [email protected] ', ' awlkdjawldkjalwdkda']
>>> list1[1].strip()
'[email protected]'
If you split a given string using substring "||" you'll receive a list of three elements. E-mail will be the second one, and the strip() function will give you the email without whitespace characters.
If you don't know exact structure of strings, but you know what substrings you want to extract you can use regular expressions, there are quite a few recipes for it, here is one for emails.
If you're allergic to REs, you could use pyparsing:
>>> import pyparsing as p
>>> ope, clo, com = map(p.Suppress, '(),')
>>> w = p.Word(p.alphas)
>>> s = ope + w + com + w + com + ope + p.delimitedList(w) + clo + clo
>>> x = '(xx,yyy,(aa,bb,cc))'
>>> list(s.parseString(x))
['xx', 'yyy', 'aa', 'bb', 'cc']
pyparsing also makes it easy to control the exact form of results (e.g. by grouping the last 3 items into their own sublist), if you want. But I think the nicest aspect is how natural (depending on how much space you want to devote to it) you can make the "grammar specification" read: an open paren, a word, a comma, a word, a comma, an open paren, a delimited list of words, two closed parentheses (if you find the assignment to s above not so easy to read, I guess it's my fault for not choosing longer identifiers;-).
If your parenthesis nesting can be arbitrarily deep, then regexen won't do, you'll need a state machine or a parser. Pyparsing supports recursive grammars using forward-declaration class Forward:
from pyparsing import *
LPAR,RPAR,COMMA = map(Suppress,"(),")
nestedParens = Forward()
listword = Word(alphas) | '...'
nestedParens << Group(LPAR + delimitedList(listword | nestedParens) + RPAR)
text = "(xx,yyy,(aa,bb,...))"
results = nestedParens.parseString(text).asList()
print results
text = "(xx,yyy,(aa,bb,(dd,ee),ff,...))"
results = nestedParens.parseString(text).asList()
print results
Prints:
[['xx', 'yyy', ['aa', 'bb', '...']]]
[['xx', 'yyy', ['aa', 'bb', ['dd', 'ee'], 'ff', '...']]]