TypeError: cannot concatenate 'str' and '_sre.SRE_Match' objects

3.5k Views Asked by At

I'm retrieving a string with regex, and I'm trying to concatenate that with other pieces of string.

Error:

TypeError: cannot concatenate 'str' and '_sre.SRE_Match' objects

Example:

original_string = "ABC 4x DEF"
regex = re.search(r"(\d)X|x", original_string)
new_string = "+" + regex + "00"
print "New string: %s" % new_string

new_string should be "+400" if everything works.

2

There are 2 best solutions below

0
On BEST ANSWER

regex is not a string. It is a Match Object representing the match. You'll have to pull the matched text:

fundleverage = "+" + regex.group(1) + "0"

Note that your expression matches either a digit with a capital X or it matches a lowercase x (no digit). In your case that means it matched the x, and group 1 is empty (None)..

To match the digit and either x or X, use:

regex = re.search(r"(\d)[Xx]", original_string)

or use case-insensitive matching:

regex = re.search(r"(\d)x", original_string, flags=re.IGNORECASE)

Demo:

>>> import re
>>> original_string = "ABC 4x DEF"
>>> regex = re.search(r"(\d)X|x", original_string)
>>> regex
<_sre.SRE_Match object at 0x10696ecd8>
>>> regex.group()
'x'
>>> regex.groups()
(None,)
>>> regex = re.search(r"(\d)x", original_string, flags=re.IGNORECASE)
>>> regex.group()
'4x'
>>> regex.groups()
('4',)
>>> regex.group(1)
'4'
0
On

For case insensitive match, use (?i).

original_string = "ABC 4x DEF"
regex = re.search(r"(\d)x(?i)", original_string)
new_string = "+" + regex.group() + "00"
print "New string: %s" % new_string

New string: +4x00