Regular Expression - String display issue

Hi there,
I tried to concatenate str which is the output of the regular expression search function. Through all, the logic seems fine and executable but I am unable to concatenate the string variable in print statement.


import re



PhoneNum_RegEx = re.compile(r'(\d{2})-(\d{10})')
mo = PhoneNum_RegEx.search('My mobile number is 21-9999999999.')

def country_code(num):
    if mo.group(1) == 21:
        print('XXXX')


print('The country code is ' + str(mo.group(1))  + ' and the country code is ' +
      country_code(mo.group(1))  + ' and the mobile number is ' + str(mo.group(2)))


In print call is used result of call to country_code function. Because country_code function doesn’t return anything explicitly, it returns None. This results in trying to concatenate None with str and because of that TypeError is raised.

Thank you Sanity. By chance, If the condition returns Val which contains the value from the condition statement then it has to return right…!!!

import re



PhoneNum_RegEx = re.compile(r'(\d{2})-(\d{10})')
mo = PhoneNum_RegEx.search('My mobile number is 21-9999999999.')

def country_code(num):
    if mo.group(1) == 21:
            val = 'country'
            return val


print('The country code is ' + str(mo.group(1))  + ' and the country code is ' +
      country_code(mo.group(1))  + ' and the mobile number is ' + str(mo.group(2)))

Please suggest

Hi There, We’ve enormous methods in Regular expression where finditer is the best out of it for all fixtures. This would solve all the issues.

Had a similar problem - thanks a lot, very helpful!

Hi riyaz,

perhaps you can share a link to the programming challenge so I can try out your code.

On the first look I wonder why your country_code function takes a num function parameter but does not use it. I would assume you want to use it in the call of mo.group.

Another little hint: you don’t have to assign the value 'country' to a variable in order to return it in the function country_code.

You can return the String with return 'country' instead.

best,
Dennis

Understood Dear @gdennci

1 Like