-2

I'm trying to edit a Python module, but I'm not getting the value I expect from a variable. The code is:

    def populate_ipv4_interfaces(self, data):
    for key, value in data.items():
        vrf = re.findall(r'VPN Routing/Forwarding "(.+)"', value)

where I'm expecting a string value to be output. It does contain my string, but something else. When I force it to be a string like this:

vrf = str(re.findall(r'VPN Routing/Forwarding "(.+)"', value))

gives me the value "[u'Internet']" instead of "Internet".

I've looked up the u, and I realise this denotes a unicode character, but I don't know why it's pulling that information along with the string.

If it helps, this is an ansible module, but I've narrowed it down to this one variable, since if I specify a string in the fact instead of this variable, everything works as intended.

Can someone tell me why I'm seeing this behaviour?

ForceBru
  • 43,482
  • 10
  • 63
  • 98
Soop
  • 345
  • 5
  • 19
  • 3
    "where I'm expecting a string value to be output" - [`re.findall` returns a list](https://docs.python.org/3.9/library/re.html#re.findall). – ForceBru Nov 04 '20 at 17:01

2 Answers2

2

re.findall returns a list of results - even if there is only one result.

And unicode strings are still strings. It should behave the same for all puposes.

So the result you are looking for is:

vrf = re.findall(r'VPN Routing/Forwarding "(.+)"', value)[0]

Don't use the str on the result directly.

rdas
  • 20,604
  • 6
  • 33
  • 46
1

re.findall() returns a list, so use a join for getting them:

vrf = ' '.join(re.findall(r'VPN Routing/Forwarding "(.+)"', value))

Other way use list indexing to get first item:

vrf = re.findall(r'VPN Routing/Forwarding "(.+)"', value)[0]
Wasif
  • 14,755
  • 3
  • 14
  • 34