-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
  • 12,464
  • 7
  • 65
  • 73
  • 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
  • 23,663
  • 10
  • 44
  • 50
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
  • 30,023
  • 4
  • 23
  • 41
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,741
  • 21
  • 29