Pradhan A
Pradhan A

Reputation: 1

Declaring a variable inside another variable

I need to declare a variable in Python in this manner, but it's not working out.

name = raw_input('Enter Name: ')

var1 = /dir_1/dir_2/% (name)

print (var1)

Expected Output :- ::/dir_1/dir_2/my custom entered name.

Upvotes: 0

Views: 6830

Answers (4)

smac89
smac89

Reputation: 43098

Since this is an file name, it makes sense to join them using the os.path module. This will ensure that the current format for the file is used when the program is run on different OS's. In particular the function to use is os.path.join

import os

name = raw_input('Enter Name: ')
var1 = os.path.normpath(os.path.join("/dir_1/dir_2", name))
print (var1)

On windows, you get something like:

\\dir_1\\dir_2\\name.txt

On Linux or unix based systems, this will return

/dir_1/dir_2/fname.txt

You might not need it for your case, but it is always nice to know this when you need code that should be portable.

Upvotes: 0

beoliver
beoliver

Reputation: 5759

You can either concatenate the strings using +

>>> 'foo' + 'bar'
'foobar'

or you can use the printf style

>>> 'foo%s' %('bar')
'foobar'

I would suggest concatenation.

name = raw_input('Enter Name: ')

var1 = '/dir_1/dir_2/' + name

print (var1)

Upvotes: 1

danidee
danidee

Reputation: 9624

You could concatenate the strings

name =raw_input('Enter Name: ')

var1 = '/dir_1/dir_2/' + name

print (var1)

Upvotes: 1

Pawan
Pawan

Reputation: 1605

Use this:

name =raw_input('Enter Name: ')
var1 = "/dir_1/dir_2/%s" %(name)
print (var1)

Upvotes: 1

Related Questions