tags:

views:

198

answers:

4
+4  Q: 

python and %s

What does %s mean in python? And does this bit of code translate to?

for instance...

 if len(sys.argv) < 2:
     sys.exit('Usage: %s database-name' % sys.argv[0])

 if not os.path.exists(sys.argv[1]):
     sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

Thanks

+13  A: 

It is a string formatting syntax (which it borrows from C).

Please see Formatting Strings:

Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder.

Edit: Here is a really simple example:

name = raw_input("who are you?")
print "hello %s" % (name,)

The %s token allows me to insert (and potentially format) a string. Notice that the %s token is replaced by whatever I pass to the string after the % symbol. Notice also that I am using a tuple here as well (when you only hava one string using a tuple is optional) to illustrate that multiple strings can be inserted/formatted in one statement.

Andrew Hare
Thanks both of you. very helpful!
Tyler
+2  A: 

'%s' indicates a conversion type of 'string' when using python's string formatting capabilities. More specifically, '%s' converts a specified value to a string using the str() function. Compare this with the '%r' conversion type that uses the repr() function for value conversion.

Take a look at the following: http://docs.python.org/library/stdtypes.html#string-formatting-operations

Brandon E Taylor
+2  A: 

In answer to your second question: What does this code do?...

This is fairly standard error-checking code for a Python script that accepts command-line arguments.

So the first if statement translates to: if you haven't passed me an argument, I'm going to tell you how you should pass me an argument in the future, e.g. you'll see this on-screen:

Usage: myscript.py database-name

The next if statement checks to see if the 'database-name' you passed to the script actually exists on the filesystem. If not, you'll get a message like this:

ERROR: Database database-name was not found!

From the documentation:

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

Adam Bernier
+2  A: 

Andrew's answer is good.

And just to help you out a bit more, here's how you use multiple formatting in one string

"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".

If you are using ints instead of string, use %d instead of %s.

lyrae