MasterHolbytla
MasterHolbytla

Reputation: 177

Python detect character surrounded by spaces

Anyone know how I can find the character in the center that is surrounded by spaces?

1 + 1

I'd like to be able to separate the + in the middle to use in a if/else statement.

Sorry if I'm not too clear, I'm a Python beginner.

Upvotes: 0

Views: 2536

Answers (5)

sal
sal

Reputation: 3593

Not knowing how many spaces separate your central character, then I'd use the following:

s = '1 +   1'
middle = filter(None, s.split())[1]
print middle  # +

The split works as in the solution provided by Zac, but if there are more than a single space, then the returned list will have a bunch of '' elements, which we can get rid of with the filter(None, ) function.

Then it's just a matter of extracting your second element.

Check it in action at https://eval.in/636622

If we look at it step-by-step, then here is how it all works using a python console:

>>> s = '1 +   1'

>>> s.split()
['1', '+', '', '', '1']

>>> filter(None, s.split())
['1', '+', '1']

>>> filter(None, s.split())[1]
'+'

Upvotes: 0

TheLazyScripter
TheLazyScripter

Reputation: 2665

import re

def find_between(string, start_=' ', end_=' '):
    re_str = r'{}([-+*/%^]){}'.format(start_, end_)
    try:
        return re.search(re_str, string).group(1)
    except AttributeError:
        return None

print(find_between('9 * 5', ' ', ' '))

Upvotes: 0

D-Von
D-Von

Reputation: 426

This regular expression will detect a single character surrounded by spaces, if the character is a plus or minus or mult or div sign: r' ([+-*/]) '. Note the spaces inside the apostrophes. The parentheses "capture" the character in the middle. If you need to recognize a different set of characters, change the set inside the brackets.

If you haven't dealt with regular expressions before, read up on the re module. They are very useful for simple text processing. The two relevant features here are "character classes" (the square brackets in my example) and "capturing parentheses" (the round parens).

Upvotes: 1

Zac Nixon
Zac Nixon

Reputation: 66

I think you are looking for something like the split() method which will split on white space by default.

Suppose we have a string s

s = "1 + 1"
chunks = s.split()
print(chunks[1]) # Will print '+'

Upvotes: 5

shiva
shiva

Reputation: 2699

You can use regex:

s="1 + 1"
a=re.compile(r' (?P<sym>.) ')
a.search(s).group('sym')

Upvotes: 0

Related Questions