0

In the code block below, I understand that s is the string. re.split() will generate a list of split results and the list comprehension will iterate through every result created.

I don't understand how "if i" will work here.

This is from the following stackoverflow thread: https://stackoverflow.com/a/28290501/11292262

s = '125km'
>>> [i for i in re.split(r'([A-Za-z]+)', s) if i]
['125', 'km']
>>> [i for i in re.split(r'(\d+)', s) if i]
['125', 'km']
Pythonner12
  • 123
  • 1
  • 1
  • 8

1 Answers1

2

Empty strings evaluate to False. Note what happens when we take the if out:

import re
s = '125km'

print(re.split(r'([A-Za-z]+)', s))
print(re.split(r'(\d+)', s))

Output:

['125', 'km', '']
['', '125', 'km']

The if is used to remove the empty string, which is unwanted, per that question. Note that the capture groups in both expressions are needed to ensure that the part of the string split on (value or unit) is also returned.

gmds
  • 19,325
  • 4
  • 32
  • 58
  • Ah okay, great, this makes sense! I assumed you'd have to write if i = '' or something. Is "if variable" something that's baked into python as a function? – Pythonner12 May 09 '19 at 13:27