Search code examples
pythonstring-formattingnested-lists

Assigning range of numbers to a letter in python


Is it possible to assign range of numbers to a letter in python, without getting into the loop, I am trying to print a row of numbers separated by pipe,these rows will be the index of a list contents so it depends on the length of the list,so if the length of the list was (4) the output would look like this:


| | 0 | 1 | 2 | 3 |

I can't use a for loop sice it will keep printing everything so:

length=len(list)

for i in range (length):

print (("|","%5s"%("|"),"%7d"%(i))    

I can't do this since it will print everything over

I was thinking about something without going the loop it's self ,some letter to save the set of numbers, so maybe I am asking about something like this(i know it's not possible this way but,something similar maybe?):

i in range (length)

and then loop only the "i" value using a while loop!


Solution

  • Use the end argument of print to control the line end behavior. Setting end to an empty string will remove the default newline; that way, multiple print statements can write on a single line.

    Example:

    print('| ', end='')
    for i in range(4):
        print(str(i) + ' | ', end='')
    

    Output:

    | 0 | 1 | 2 | 3 |