Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does %s mean in a python format string?

What does %s mean in Python? And what does the following bit of code do?

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]) 
like image 373
Tyler Avatar asked Jun 15 '09 19:06

Tyler


People also ask

What is %s and %D in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))

What is %s in Python print?

%s acts as a placeholder for the real value. You place the real value after the % operator. This method is often referred to as the "older" way because Python 3 introduced str. format() and formatted string literals (f-strings).

What does %s mean in Python 3?

The %s operator lets you add a value into a Python string. The %s signifies that you want to add a string value into a string. The % operator can be used with other configurations, such as %d, to format different types of values.


2 Answers

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

Please see "PyFormat":

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.

Here is a really simple example:

#Python 2 name = raw_input("who are you? ") print "hello %s" % (name,)  #Python 3+ name = 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 have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.

like image 150
Andrew Hare Avatar answered Oct 06 '22 01:10

Andrew Hare


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.

"My name is %s and I'm %d" % ('john', 12) #My name is john and I'm 12 
like image 42
sqram Avatar answered Oct 06 '22 01:10

sqram