Python bug, or am I misunderstanding something?

  • Python
  • Thread starter Borek
  • Start date
  • #1
Borek
Mentor
28,396
2,799

Main Question or Discussion Point

I don't know python, yet I am trying to code something, just for fun. But I have hit some strange obstacle and I don't know if it is a bug in my Python version (dated, it is over a year old, under Raspbian), or is it me misunderstanding something?

Code:
pattern = re.compile('\[(\d+)\]\[(\d+)\](.*)')
line = '[123][456]789'
print 'original string:'
print line
m = pattern.match(line)
print 'matched substrings:'
print m.groups()
fst = '[{}][{}]{}'
print 'output using strings returned from m.group():'
print fst.format(m.group(0), m.group(1), m.group(2))
print 'output using just strings:'
print fst.format('123','456','789')
Output:

Code:
original string:
[123][456]789
matched substrings:
('123', '456', '789')
output using strings returned from m.group():
[[123][456]789][123]456
output using just strings:
[123][456]789
Why is the output using m.group() strings garbled? Strings are matched correctly, m.group() returns a string, so it should work the same way it works in the last output line - but it doesn't. I understand [] can be used to access arguments’ items, but I don't see a way of escaping them, besides, it doesn't seem to be a problem in other cases.

The simplest thing to try would be to upgrade to the newest python version, but I am unable to. I get message that some files are missing and suggestion to do full update - which I don't want to try, as I was not able to setup my WiFi dongle on another Pi with the newest Raspbian.
 

Answers and Replies

  • #2
jhae2.718
Gold Member
1,161
20
Try:
Code:
print fst.format(m.group(1), m.group(2), m.group(3))
m.group(0) returns the entire string '[123][456]789'.
 
  • Like
Likes 1 person
  • #3
Borek
Mentor
28,396
2,799
Thanks. Much better now.

Will see if that's the end of the story :wink:
 

Related Threads on Python bug, or am I misunderstanding something?

Replies
3
Views
2K
Replies
31
Views
3K
Replies
2
Views
1K
Replies
14
Views
1K
  • Last Post
Replies
0
Views
3K
  • Last Post
Replies
20
Views
32K
  • Last Post
Replies
5
Views
1K
Replies
2
Views
353
Replies
26
Views
8K
Top