Saturday, June 27, 2020

User Input and String Formatting

 User Input


Use the input() function to return a value to the variable. The input function has an optional string prompt that can be displayed to the screen. Python code will wait indefinitely for user input. 


basket = input("groceries to buy?:")
print("The food is ", basket)


After typing in the response to the keyboard at the input function's prompt, just press Enter to move the code along.


String Formatting


Use the format() function with arguments passed into the format function which will match up with pairs of curly braces in a string variable from left to right.


vacations = "There are {} , {} and {} islands."

# format is a member function of the vacations string object.
# just by making a string assignment, you have created a string 
# object and you do not need a constructor for that.

print(vacations.format("Caribbean", "Greek", "Japanese"))

# result is:

There are Caribbean, Greek, and Japanese islands.

Leaving out the curly braces in the string variable with a call to the format function will just ignore any arguments in the format function and print null instead.

vacations = "There are  ,  and islands."

# format is a member function of the vacations string object.

print(vacations.format("Caribbean", "Greek", "Japanese"))

# result is:

There are  ,  and islands.


In the case if you make a mistake where you have more curly braces in a target variable than arguments into the format function, python returns a IndexError: tuple index out of range response.

vacations = "There are {} , {} and {} islands."

# format is a member function of the vacations string object.

print(vacations.format("Caribbean", "Greek"))

# result is:

IndexError: tuple index out of range


If however on the other hand, you have a number of arguments passed into the format() which exceed the number of {} then the extra rightmost arguments are ignored and no errors are generated.

vacations = "There are {} , {} and islands."

# format is a member function of the vacations string object.

print(vacations.format("Caribbean", "Greek", "Japanese"))

# result is:

There are Caribbean, Greek, and islands.


You can specify a large number of field properties also known in python as "standard format specifiers". They allow you to fine-tune the format, placement, or style of a string.


debt = 1000000

# :e is the standard format specifier for scientific notation

pay = "I owe this much: {:e}"


print(pay.format(debt))

# result is:

I owe this much: 1.000000e+06


Arguments to a format function call can be comma separated or key-value pairs or both. They can be of any data type including an index.



There are three options for formatting the curly braces pairs in a target string variable: 


1. You can put the name of a key in the {}; in that case a key-value pair must be passed in for the format function.


dessert = "I like {cookie} cookies, {cake} cakes and {ice_cream} ice cream."

print(dessert.format(cookie = "oatmeal raisin", cake = "vanilla", ice_cream = "strawberry"))

# result is:


I like oatmeal raisin cookies, vanilla cakes and strawberry ice cream.


2. You can use an integer index starting as low as 0 to indicate which of the members of the argument collection in the format call are to be inserted in various places. Placement can be out of order and also arguments can be skipped (not used). It must be in list format; no key=value pairs are allowed.

dessert = "I like {0} cookies, {1} cakes and {2} ice cream."

print(dessert.format(cookie = "oatmeal raisin", cake = "vanilla", ice_cream = "strawberry"))

# result is an error because you used key-value pairs:

IndexError: tuple index out of range

dessert = "I like {0} cookies, {1} cakes and {2} ice cream."

print(dessert.format("oatmeal raisin", "vanilla", "strawberry"))

# result is valid because the flavors are given as a list:

I like oatmeal raisin cookies, vanilla cakes and strawberry ice cream.

This also works, but note you have to index into the list.

foods = ["oatmeal raisin", "vanilla", "strawberry"]
dessert = "I like {0} cookies, {1} cakes and {2} ice cream."

print(dessert.format(foods[0], foods[1], foods[2]))

# result is:

I like oatmeal raisin cookies, vanilla cakes and strawberry ice cream.

3. If you just have a plain empty pair of {} you can use a list or key value pairs.

dessert = "I like {} cookies, {} cakes and {} ice cream."
# arguments as a list
print(dessert.format("oatmeal raisin", "vanilla", "strawberry"))

# result is:

I like oatmeal raisin cookies, vanilla cakes and strawberry ice cream.

The same result is achieved with:

dessert = "I like {a} cookies, {b} cakes and {c} ice cream."
# arguments as key-value pairs
print(dessert.format(a = "oatmeal raisin", b = "vanilla", c = "strawberry"))

# result is:

I like oatmeal raisin cookies, vanilla cakes and strawberry ice cream.


You can even mix key=value pairs and list items in the same format() call:

dessert = "I like {} cookies, {b} cakes and {c} ice cream."

print(dessert.format("oatmeal raisin", b = "vanilla", c = "strawberry"))

# result is:

I like oatmeal raisin cookies, vanilla cakes and strawberry ice cream.


Python is even smart enough to handle key-value pairs and list items out of order:

dessert = "I like {b} cookies, {} cakes and {c} ice cream."

print(dessert.format("oatmeal raisin", b = "vanilla", c = "strawberry"))


# result prints without errors but now the cookies are vanilla and cakes are oatmeal raisin:

I like vanilla cookies, oatmeal raisin cakes and strawberry ice cream.


However, forgetting one of the keys, which is the same as having too many empty {} in a mixed call, will confuse Python and generate an error:

# the b key is left out by mistake, and there are more {} than list items now.

dessert = "I like {} cookies, {} cakes and {c} ice cream."
# oatmeal raisin is a list-type item
print(dessert.format("oatmeal raisin", b = "vanilla", c = "strawberry"))


# result is

IndexError: tuple index out of range


When you're using field properties, again also known as standard format specifiers, you only use the colon once, even if you have multiple options passed in. If you try to use two colons - say one for each of two options - python kicks back a ValueError.

boats = 334
marinas = 7

# :+ puts a plus sign in front of positive numbers by brute force
# :e is for scientific notation
# a specifier of :+:e will generate an error; drop the rightmost of the colons as shown correctly below.

docking = "{1:+e} boats are too many for {0} marinas."

print(docking.format(marinas, boats))

# result is:

+3.340000e+02 boats are too many for 7 marinas.

The example above also works without a run-time python error if you leave off the index of 0 and 1 since variables are being passed in.  However, the meaning of the sentence is confused, so be careful about using indices out of order.


boats = 334
marinas = 7

# :+ puts a plus sign in front of positive numbers by brute force
# :e is for scientific notation
# a specifier of :+:e will generate an error; drop one of the colons as shown correctly below.

docking = "{:+e} boats are too many for {} marinas."

print(docking.format(marinas, boats))

# result is:

+7.000000e+00 boats are too many for 334 marinas.


However, with strings passed in, it will fail because specifiers won't work with pure strings.


docking = "There are only 7 {0} for 334 {1:+e}."

print(docking.format("bays", "ships"))

# results in:

ValueError: Unknown format code 'e' for object of type 'str'


# Also incorrect:

docking = "There are only 7 {} for 334 {1:+e}."

print(docking.format("bays", "ships"))

# results in:

ValueError: cannot switch from automatic field numbering to manual field specification, meaning, mixing empty parentheses with indexed parentheses.


However, turning "ships" into a proper variable gets the job done without error. 

Also, mixing variables and string list items in a format() function call is valid code.

ships = 334

# standard format specifiers and open parentheses are OK 
# in the same string.

docking = "There are only 7 {} for {:e} ships."

print(docking.format("bays", ships))

# results in:

There are only 7 bays for 3.340000e+02 ships.

Finally, you can even use the same index more than once.

docking = "There are only 7 {1} for 334 {1}."

print(docking.format("bays", "ships"))

# results in:

There are only 7 ships for 334 ships.



Anyhow, you get the idea that there many permutations for mixing and matching index vs. empty curly braces vs. variables vs. key=value pairs for getting the format function to handshake with {} in a target string variable.


See the following website for the full description of all the standard format specifiers, also known as custom string formaters:


 a few examples are:

 :,       --> display thousands separator


 :e      --> for scientific format


:f       --> fixed point number format 

:>      --> right align the result


No comments:

Post a Comment