Home > Enterprise >  How do I assign output from a loop as a variable
How do I assign output from a loop as a variable

Time:09-14

I currently have this list: ['/', 'home', 'documents', 'pictures']

and I have this loop:

for i, dir in enumerate(path):
    if i == 0:
        print(dir, end="")
    elif i == len(path) - 1:
        print(dir)
    else:
        print(dir, end='/')

which will output /home/documents/pictures.

How can I assign the output of this loop to a variable?

e.g. print(var) will output /home/documents/pictures

CodePudding user response:

If you just want combine each value of in the list to a string variable. Here is my solution hopes helps you!

dir=['/', 'home', 'documents', 'pictures']
path=''
for i in dir: #read the array
    if(i!='/'):
        path ='/'
        path =i #append the new value in the String variable
    else:
        continue
print(path)

CodePudding user response:

You should assign to variable

path = ['/', 'home', 'documents', 'pictures']

var = ""

for i, dir in enumerate(path):
    if i == 0:
        var  = dir
    elif i == len(path) - 1:
        var  = dir
    else:
        var  = dir   '/'

print( var )

But it is much simpler with os.path

import os

path = ['/', 'home', 'documents', 'pictures']

var = os.path.join(*path)

print( var )
  • Related