-3

friends. I have this code in my python application:

if '(' in obj.value or ')' in obj.value:
    city, country = obj.value.upper()[:-1].split('(')
    found = city.strip() == self.customer.city.upper() and country == self.customer.country.upper()
else:
    city = obj.value.upper()
    found = city.strip() == self.customer.city.upper()

A text string that can be with the following possible values​​:

'New York' or 'New York (NY)'

But the problem is that the code below does not guarantee a possible error, for example, be missing one of the brackets. Eg

'New York NY)'

How can I improve and protect this little snippet? There is a formula in Regex, for example? (I know some regex)

Eduardo
  • 1,698
  • 4
  • 29
  • 48
  • 3
    `continue` is a reserved word in Python, btw; you cannot use it as the name of a variable. – Erik Kaplun Oct 03 '13 at 13:49
  • Thanks @ErikAllik. I Edited my example. Surely, I dont use this word. :) – Eduardo Oct 03 '13 at 13:50
  • To clarify - you want _either_ no parentheses, or _two_: an opening and a closing one, with the opening coming before the closing. Do you want just two capital letters between these parentheses? The clearer your requirements, the better the answer you get... – Floris Oct 03 '13 at 13:51
  • http://stackoverflow.com/questions/8040795/how-can-i-get-a-value-thats-inside-parentheses-in-a-string-in-python – Foo Bar User Oct 03 '13 at 13:53
  • Note also potential typo - `contry` vs `country`... – Floris Oct 03 '13 at 13:53
  • @Floris, I always need to feed the variable City. The variable Country, I feed if there is a setting between parentheses. – Eduardo Oct 03 '13 at 13:54
  • You claim you edited the example but `continue` is still there. – Adam Spiers Oct 03 '13 at 13:55
  • What do you want to do with the string `New York NY)`? – Floris Oct 03 '13 at 13:55
  • Also you should remove the `upper()` stuff from the question, because it is not relevant and just confuses the issue. – Adam Spiers Oct 03 '13 at 13:57
  • Finally, please fix the question title to relate to the question. You really should read [How to Ask](http://stackoverflow.com/questions/how-to-ask) and [Writing the perfect question](http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx) before asking more questions. – Adam Spiers Oct 03 '13 at 14:01
  • Just a guess that it is required to get the city name and its abbreviated name. Like: New York (NY) -> 'New York', 'NY' Los Angeles (LA) -> 'Los Angeles', 'LA' – gsmaker Oct 03 '13 at 14:03
  • @gsmaker - I suspect that the bit in parentheses is the state (so it would be `Los Angeles (CA)` ). Or, as the code would have it, the `contry`. – Floris Oct 03 '13 at 14:46

1 Answers1

2
import re
m = re.match('(.+) \((.+)\)', obj.value)
if m:
    city, country = m.groups()
else:
    city, country = obj.value, None
Adam Spiers
  • 17,397
  • 5
  • 46
  • 65