-2

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.

P A N
  • 5,642
  • 15
  • 52
  • 103
  • 3
    Your posted code does not define any variable called `regex_fundleverage`. Have you read [the documnetation](https://docs.python.org/2/library/re.html) to understand what match objects are, where you get them, and how to use them? – BrenBarn Jun 16 '15 at 21:29
  • Can see more here http://stackoverflow.com/questions/18493677/how-do-i-return-a-string-from-a-regex-match-in-python – Bhargav Rao Jun 16 '15 at 21:30
  • @BrenBarn Sorry, edited. It should just be variable `regex`. – P A N Jun 16 '15 at 21:32

2 Answers2

6

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

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

Nizam Mohamed
  • 8,751
  • 24
  • 32