shadeless
shadeless

Reputation: 115

python regexp method returns a list with an empty element

I am learning how to use regular expressions in python. I am searching for a pattern in a string and returning a value in that string. Here is the code that I have so far.

import re

string = '20180515_154457_Trace3_110K_2_data.dpt'
pattern = r'_Trace3_(\d+)K_\d+_data.dpt'
re.search(pattern,  string).groups()

The above returns ('110', ). Why doesn't it just return ('110')? Why does it give me a tuple with an empty second element?

Upvotes: 1

Views: 43

Answers (3)

Ryan Schaefer
Ryan Schaefer

Reputation: 3120

For a tuple to be considered a tuple, it must have the "second" element.

If it were just one element, it would just be the data.

example:

>> x = ('test')
>> x
'test'
>> x = ('test',)
>> x
('test', )

In your case you can just do:

variable = re.search(pattern, string).groups()[0]

Upvotes: 1

N Chauhan
N Chauhan

Reputation: 3515

The line...

('110', ) 

...Is a single-element tuple. This distinguishes it from a parenthesised expression. The trailing comma is part of Python syntax and as I said, it is a single element tuple despite how it looks.

If it were just...

('110')

... this is just a string.

Upvotes: 2

heemayl
heemayl

Reputation: 42007

Why does it give me a tuple with an empty second element?

Nope. That's a tuple with a single element.

('110') is a string, whereas ('110',) is a tuple of one element.

You can always clarify yourself by a simple type run:

In [1584]: type(('110'))
Out[1584]: str

In [1585]: type(('110',))
Out[1585]: tuple

As an additional note, the parentheses (()) are there just to avoid ambiguity, it would be treated as a tuple without it as well in any unambiguous case:

In [1587]: foo = 100,

In [1588]: type(foo)
Out[1588]: tuple

Upvotes: 3

Related Questions