简体   繁体   English

在另一个变量中声明一个变量

[英]Declaring a variable inside another variable

I need to declare a variable in Python in this manner, but it's not working out. 我需要以这种方式在Python中声明一个变量,但无法正常工作。

name = raw_input('Enter Name: ')

var1 = /dir_1/dir_2/% (name)

print (var1)

Expected Output :- ::/dir_1/dir_2/my custom entered name . 预期输出:- ::/dir_1/dir_2/my custom entered name

Use this: 用这个:

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

You could concatenate the strings 您可以连接字符串

name =raw_input('Enter Name: ')

var1 = '/dir_1/dir_2/' + name

print (var1)

You can either concatenate the strings using + 您可以使用+连接字符串

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

or you can use the printf style 或者您可以使用printf样式

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

I would suggest concatenation. 我建议串联。

name = raw_input('Enter Name: ')

var1 = '/dir_1/dir_2/' + name

print (var1)

Since this is an file name, it makes sense to join them using the os.path module. 由于这是一个文件名,因此可以使用os.path模块将它们连接起来。 This will ensure that the current format for the file is used when the program is run on different OS's. 当程序在不同的OS上运行时,这将确保使用文件的当前格式。 In particular the function to use is os.path.join 特别是要使用的函数是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: 在Windows上,您会得到类似以下内容的信息:

\\dir_1\\dir_2\\name.txt

On Linux or unix based systems, this will return 在基于Linux或Unix的系统上,这将返回

/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. 您可能不需要它,但是当您需要可移植的代码时,很高兴知道这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM