1 / 15

Python Print Function and String Formatting

Learn how to suppress print space, newline, escape characters, and strip whitespace in Python. Also, explore formatting numbers, setting number width, percentages, and the use of constants.

marybsmith
Download Presentation

Python Print Function and String Formatting

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Suppressing print Space • print function uses a space to separate items in print statement • To suppress the print between items printed use • Special argument sep='delimiter' • Causes print to use delimiter as item separator • Delimiter is usually no space in this case ‘’, but can be anything >>> print (‘One’,’Two’,’Three’, sep=’’) Output: OneTwoThree

  2. Suppressing print Newline • print function usually goes to next line when done • A feature allows you to suppress newline • Argument end='delimiter' causes print to place delimiter at end of print output • Delimiter can be what you want, • Usual delimiters • Is set to Space :‘ ‘ • Or no space: ‘’ Print(‘One’, end=‘ ‘) Print(‘Two’, end=‘ ‘) Print(‘Three’) Output One Two Three

  3. Escape Characters • Special characters appearing in string literal • Preceded by backslash (\) • Examples: newline (\n), horizontal tab (\t) • Treated as commands inside a string print(‘One\nTwo\nThree’) Output: One Two Three print(‘Mon\tTue\tWed’) print(‘Thu\tFri\tSat’) Output: Mon Tue Wed Thu Fri Sat

  4. Stripping Whitespace • Whitespace is any nonprinting character • Examples: Spaces, tabs, end-of-line symbols • Spaces in a string can be confusing to a program • Ex: 'python ' and 'python' look the same to humans, but not to Python. It sees the extra space at the end. • Useful when user adds space at end of username • Can look for extra spaces on right and left of string • rstrip() removes spaces on right of string • lstrip() removes spaces on left of string • strip() removes spaces from both sides

  5. Stripping Whitespace Example fav_language = 'python ' # Notice extra space print(fav_language.rstrip()) Produces Python with no extra space fav_language = ' python ' # Notice extra spaces print (fav_language.strip()) Produces Python with no spaces on either side

  6. Formatting Numbers • format function: can format floating point numbers up to 12 significant digits • format(numeric_value, format_specifier) • Returns string containing formatted number • Format specifier typically includes precision and data type • Format: ‘decimal_width(type)’ • Ex: ‘2f’ for 2 digits after decimal point • Numbers >= 5 are rounded up >>> print(format(123.4567, ‘.2f’) 123.46

  7. Comma Separator • Allows you to include commas in numbers >999 • Place a comma before the . in the formatting string • Ex: ‘,.2f’ big_number = 12568.789 print (format(big_number,',.2f')) Output: 12,568.79

  8. Formatting Numbers Examples # This program demonstrates how a floating-point # number can be displayed as currency. # Notice the use of sep= so $ is next to number monthly_pay = 5000.0 annual_pay = monthly_pay * 12 print('Your annual pay is $', \ format(annual_pay, ',.2f'), sep='') Output: Your annual pay is $60,000.00

  9. Setting Number Width • Determine width of number: • Format: '[field_width] decimal_width(type)' • Ex: '12.2f' will create a 12 character wide floating point number with two digits after the decimal

  10. Formatting Field Width Example num1 = 127.899 num2 = 3465.148 num3 = 3.776 num4 = 264.821 # Display each number in a field of 7 spaces # with 2 decimal places. print(format(num1, '7.2f')) print(format(num2, '7.2f')) print(format(num3, '7.2f')) print(format(num4, '7.2f')) Output: 127.90 3465.15 3.78 264.82

  11. Formatting Number as Percentage • The % symbol can be used in the format string to format a number as a percentage • Percentages are usually fractions with numbers after the decimal place, but they are written as if you multiplied that number by 100 • Ex: 0.05 is 50% >>> print(format(0.5, ‘%’)) # Default width 50.000000% >>> print(format(0.5, ‘0%’)) # has no digit after # decimal 50%

  12. Formatting Integers • To format an integer using format function: • Use d as the type designator • Do not specify precision • Can set field width or comma separator >>> print(format(123456,’d’)) 123456 >>> print(format(123456,’,d’)) 123,456

  13. Undefined Constant • An unexplained numeric value that appears in a program’s code. Example:amount = balance * 0.069 • What is the value 0.069? An interest rate? A fee percentage? Only the person who wrote the code knows for sure. interest_rate = 0.069 amount = balance * interest_rate

  14. Reason To Use Constants • It can be difficult to determine the purpose of the number. • It can take a lot of effort to change the number in multiple locations. • Risk of making a mistake each time you type the number in the program’s code. • Ex: suppose you intend to type 0.069, but you accidentally type .0069. This mistake will cause mathematical errors that can be difficult to find.

More Related