Search code examples
pythonstartswithends-with

If condition with startswith and endswith error


I have the split the data that starts from ( and ends ) x contains data likes (33)Knoxville, TN,,,(1)Basking Ridge, NJ location = "".join(x.split("()"))[4:] in this split logic what condition should I gve [3:] ??

           if name:

        if x.startswith('(') and x.endswith(')'):

            location = "".join(x.split("()"))[3:]

            print(location)
        else:
            location = x

Solution

  • Hope you are trying to split by (chars) or ,,

    >>> s = '(1)Basking Ridge, NJ (33)Knoxville, TN'
    >>> import re
    >>> re.split(r'\s*\([^()]*\)\s*|\s*,\s*', s)
    ['', 'Basking Ridge', 'NJ', 'Knoxville', 'TN']
    >>> t = re.split(r'\s*\([^()]*\)\s*|\s*,\s*', s)
    >>> ','.join([i for i in t if i])
    'Basking Ridge,NJ,Knoxville,TN'
    >>>