-4
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?

Georgy
  • 9,972
  • 7
  • 57
  • 66
  • The `if` statement in Python is not an expression and does not have a value. It cannot be assigned to a variable. – DYZ May 10 '20 at 08:56
  • Does this answer your question? [How to pad zeroes to a string?](https://stackoverflow.com/questions/339007/how-to-pad-zeroes-to-a-string) – Georgy May 10 '20 at 09:50

3 Answers3

1

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'
Thierry Lathuille
  • 22,718
  • 10
  • 38
  • 45
1

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
Valdi_Bo
  • 27,886
  • 3
  • 21
  • 36
0

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)
        ...
scriptmonster
  • 2,611
  • 20
  • 29