for i in range(1,50):
path = if i < 10:
url + '0' + str(i)
else:
url + str(i)
df = pd.read_html(path)
in this situation, I got
SyntaxError: invalid syntax for 'if'.
how can I fix this code?
for i in range(1,50):
path = if i < 10:
url + '0' + str(i)
else:
url + str(i)
df = pd.read_html(path)
in this situation, I got
SyntaxError: invalid syntax for 'if'.
how can I fix this code?
Keep it simple and explicit and just do:
if i < 10:
path = url + '0' + str(i)
else:
path = url + str(i)
Or, use Python's string formatting capabilities to create your string. If you want a zero-padded string with a minimal length of 2 characters, you can use the following format:
>>> a = 3
>>> f'{a:0>2}'
'03'
>>> a = 33
>>> f'{a:0>2}'
'33'
>>> a = 333
>>> f'{a:0>2}'
'333'
You actually want to "reformat" the path, converting i to a zero-padded string. So the most natural way is to use just the zero-padded formatting, accessible among others in f_strings. Something like:
for i in range(1,50):
path = url + f'{i:02}'
# Do with your path whatever you wish
If you want to use if statement in assignment you can do the following:
path = url + '0' + str(i) if i < 10 else url + str(i)
thus your code inside the loop will be like the following:
for i in range(1,50):
path = url + '0' + str(i) if i < 10 else url + str(i)
df = pd.read_html(path)
...
There is an another approach for your goal. You need to zero pad the number to make it 2 characters, so you can use zfill
method of str class.
for i in range(1,50):
padded_i = str(i).zfill(2)
path = '{url}{id}'.format(url=url, id=padded_i)
df = pd.read_html(path)
...
You can use traditional way as well but it's not sweet as the previous ones:
for i in range(1, 50):
if i < 10:
i = '0' + str(i)
else:
i = str(i)
path = url + i
df = pd.read_html(path)
...