简体   繁体   中英

regarding the parameter for imp.load_source

I once saw the following python code. Here f represents a full path pointing to a python file, I am not clear what does "arch_%s" % postfix used for? and how does postfix work here?

arch = imp.load_source("arch_%s" % postfix, f)

The first argument is just a name to reference the loaded code as a regular module, and has nothing to do with the second part of the question. The % notation is the old format notation. It's similar to printf formatting, so

"arch_%s"%post_fix

will just insert post_fix as a string ( %s - you can use others such as %d in my next example), so if post_fix=64 you would get

arch_64

It's better to use format usually, if it's not a trivial substitution and as a rule:

"arch_{}".format(post_fix)

it is called String formatting in Python. It use to append a certain string variable to anoter raw string. Therefore, in your example it will append the string stored in post_fix to the string 'arch_' .

Python 3

Since you added python-3x as a tag it is relevant to tell you that in python 3 you should use format instead. Here is a lot of goodexamples . It is actually better suited for this type of operations since it handles more wanted behavior. This is from the documentation;

This section contains examples of the new format syntax and comparison with the old %-formatting.

In most of the cases the syntax is similar to the old %-formatting, with the addition of the {} and with : used instead of %. For example, '%03.2f' can be translated to '{:03.2f}'.

The new format syntax also supports new and different options, shown in the follow examples.

Basic use cases

In python 2.x

sentence = raw_input("Enter your name?")
print "Hi %s" %name

In python 3.x

name = input("Enter your name?")
print ("Hi {}".format(name))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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