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.
regex
is not a string. It is a Match Object representing the match. You'll have to pull the matched text:Note that your expression matches either a digit with a capital
X
or it matches a lowercasex
(no digit). In your case that means it matched thex
, and group 1 is empty (None
)..To match the digit and either
x
orX
, use:or use case-insensitive matching:
Demo: