COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
PYTHON | FORMATTING DATA
ON THIS PAGE
SECTION 1 | USING SPEECH-MARKS IN A STRING 
SECTION 2 |  CHANGING THE CAPITILISATION OF A STRING

SECTION 3 | DETERMINE A DATA TYPE
SECTION 4 | USING THE .FORMAT METHOD
SECTION 5 | SLICING A STRING
SECTION 6 | STRIPPING A STRING
SECTION 7 | FORMATTING NUMBERS
SECTION 8 | PRINT A LIST AS A TABLE
SECTION 9 | REMOVE DUPLICATES FROM A LIST

ALSO IN THIS TOPIC
 GETTING STARTED 

 VARIABLES AND DATA TYPES
OPERATORS 
SELECTION 

 ITERATION
 ARRAYS
 FUNCTIONS AND PROCEDURES  
YOU ARE HERE | FORMATTING DATA 
ERROR CHECKING
OBJECT ORIENTED PROGRAMMING 
Picture
IN THIS SECTION
There are many ways that we may want to present text and numbers, such as we may wish to show numbers to 2 decimal places, or we may want to add quotations into a line of text. This section covers many of the popular ways in which you may wish to format text, numbers and printing elements from a list in a neat user-friendly way.

Many of the methods covered so far have been methods that help the learning process however, they are beginner style coding methods. Much of this section looks at improving your code and taking from beginner to making your code more efficient and looking like an advanced coder.

Hopefully removing some of the newbie habits that were a vital part of the learning process.
SECTION 1 | USING SPEECH-MARKS IN A STRING 
ADDING QUOTATION MARKS IN A STRING
You may wish to add speech-marks in your string such as: print ("The teacher said 'Well done' to all students"), to do this you will need to add a \ before your internal quotation marks, for example:
print ("The teacher said \"Well done\" to all students")
After the \ you can use single or double quotation marks.
SECTION 2 |  CHANGING THE CAPITILISATION OF A STRING
UPPER, LOWER AND TITLE METHODS
Upper() and Lower() methods - We can also convert strings to upper or lower case - particularly useful when taking a user input for example:
​myString = ("Bob Fisher")
myString2 = myString.upper() #Makes BOB FISHER uppercase
myString3 = myString.lower() #Makes bob fisher lowercase

Title() method - to convert the first letter in a word to uppercase
my_word = ("london")
my_word = my_word.title()
print (my_word)
Output: London

Input case type - You can also use these features on the same line of code that you ask the user for an input. It reduces the lines of code by converting the user input on the same line, for example:
name = input("What is your name ").lower()
SECTION 3 | DETERMINE A DATA TYPE
It is quite common to want to check what type of data a variable is holding. We can use the type method to determine the content of a string for example.

myWord = ("1")
myType = (type(myWord))
print (myType)

The output would be: <class 'str'>
Meaning that Python recognises myWord as a string, which it is because the "1" is in speech-marks. Remember that this is not so easy when taking a user input because the user might type a number but if that is stored as a string then the type return will still be str. For this the isinstance is a good method to check the type of data, the example below shows a variable containing a float and then an IF statement using the isinstance method to check the data type.

    
SECTION 4 | USING THE .FORMAT METHOD
Joining a series of strings, variables or text and numbers together is called concatenation.  We have already looked at basic concatenation in the Data Types and Variables section where we joined strings with integers and added variables to strings. Whilst it seems to make sense to just join string with the comma or + method for example: print("Hello" + firstName + lastName). This method does not always work, especially with some external data handling and some GUI situations. An alternative is using the .format method as explained below.

.format method
The format method allows you to stipulate at the end of a string what values you would like to insert. When writing the string if you place curly brackets { } where you know you would like a value to be you can then use the .format method to populate the curly brackets. As can be seen from the example below if you do not define the order in which the { }s should appear then it will take position 0 from your values after the .format command and place that value into the first bracket within your string, then repeat for position 1,2 and so on.
name1 = ("Jack")
name2 = ("Jill")
print ("{} and {} went up the hill".format(name1, name2))
Output: Jack and Jill went up the hill

.format with strings, variables and numbers - The below example shows that you can insert strings using the .format as well as variables. You can also insert numbers.
name1 = ("Jack")
print ("{} and {}".format(name1,"Jill"))
Output: Jack and Jill

.format in any order - The below example shows how you can decide which piece of data from the .format range is inserted at a particular place, in this case the value in position 1 is being used before the value in position 0.
name1 = ("Jack")
name2 = ("Jill")
print ("{1} and {0}".format(name1, name2))
Output: Jill and Jack
SECTION 5 | SLICING A STRING
Taking a string and cutting it is useful in many ways, these example show how to slice parts of a string. Let's say you want the first letters from a name then join them to create initials, the example below shows how to return the content from the index of each element in the string.
firstName = ("Jill")
lastName = ("Hill")
staffCode = (firstName[0] + lastName[0])
print (staffCode)
The output from the above example would be: JH
In the example position [0] was given to return the first letter, however the same method can be used to return a range of letters.
[:3] Would return the first 3 elements from a string
[3:] Would return from the third element until the end of the string
[2:5] Would return from the second to the forth element from the string, note it does not include the fifth.
​For example:
firstName = ("Jillian")
nickName = (firstName[:4])
print (nickName)
The output from the above example would be: Jill
SECTION 6 | STRIPPING STRINGS
If you want to split a string before or after a character within the string you can use the following to methods, firstly the method below shows stripping all data in the string before the colon ':' 

    
OUTPUT:  Friends

The below demonstrates how to strip data after a given character.

    
The partition() method is used to split the string myData at the first occurrence of the separator ':'. It returns a tuple containing three elements:
  • The part before the separator (before).
  • The separator itself (sep).
  • The part after the separator (after).
In this case, after this line:
  • before will have the value "1 Veiw".
  • sep will have the value ":".
  • after will have the value " Friends".
OUTPUT: 1 View
Another way other doing this could be to use the find method to find the point at which you want to strip and then use than point as your start or end index. Below shows this being used to remove the .com from a web address.

    
SECTION 7 | FORMATTING NUMBERS
FORMATTING DECIMAL PLACES
​There are a few methods of returning a float (decimal number) with a specified number of decimal places, firstly we can use the "%. f" method, secondly the (round(method), the splice method, and the division method.

USING THE %. F METHOD
Firstly formatting to 2dp using the "%.2f" % method:
num = 12.987654321
num2 = ("%.2f" % num)
print (num2)
By running this code you can see the output will be 12.98. You can also just print the original variable to the specified number of dp. Used if you do not need to save both the old and new values:
num = 12.987654321 print ("%.2f" % num)
ROUNDING NUMBERS
Using the round method you can round numbers to a specified number of decimal places. You need to call the round method, tell python what you want to round and then to how many decimal places you want to round the number to. For example:

num = 12.987654321
num2 = (round(num,2))
print (num2)
You will notice in the methods above all all the formatting will round, so for example the output will be 12.99. 
ROUNDING NUMBERS - DIVIDE METHOD
If you do not wish to round then you can divide by 0.01 to give you at integer of the number you require, for example 1298.7654321, then divide the answer by 100 to give you the none rounded answer of 12.98. As can be seen in the example below.
num = 12.987654321
num2 = (int(num/0.01)/100)
print (num2)
Copy and paste the code above, test and see the output. This is a useful method to use when manipulating numbers.
SECTION 8 | PRINT A LIST AS A TABLE
Displaying the content of a list in a neat and user-friendly way.
CREATE A TABLE FROM A LIST
This method show how to print a list in nice neat rows and columns. Starting with a list of star wars details and printing them in table format.
starwars = ['IV', 'A New Hope', '1977','V', 'The Empire Strikes Back', '1980',
'VI', 'Return of the Jedi', '1983', 'I', 'The Phantom Menace', '1999',
'II', 'Attack of the Clones', '2002','III', 'Revenge of the Sith', '2005',
'VII', 'The Force Awakens', '2015','VIII', 'The Last Jedi', '2017']
start = 0  #Create a starting point for each row
end = 3    #Create an end point for each row
num = (int(len(starwars)/end))    #This counts how many rows are needed in the loop
 
for i in range (num): #in this example we will loop 8 times
   print ("%-5s %-25s %s" %(starwars[start], starwars[start + 1], starwars[start+2]))
   start = end #Make the next starting point where the last loop ended
   end = end + 3 #Iterate the end point for the next row

​The print statement from the code above firstly creates place holders, large enough to hold the data, the first one is 5 spaces for the Star wars Episode number, the second placeholder 25 spaces for the Star wars Title, and lastly we do not need to define the space needed. After creating the three placeholders the three items follow each with their list positions.

Copy and paste the code, it is commented to help you. Change the code as you wish.
SECTION 9 | REMOVE DUPLICATES FROM A LIST
A quick and easy way to remove duplicates from a list is to use the set() method.

myList1 = ["Bob", "Jane", "Jenny", "Bob"]
myList2 = (list(set(myList1)))
print(myList2)
Picture
NAVIGATION
​GETTING STARTED | Downloading Python and creating Hello World
VARIABLES AND DATA TYPES | Storing data in variables
OPERATORS | Performing calculations and comparisons
SELECTION | Using IF statements
ITERATION | Using FOR Loops and WHILE Loops
ARRAYS | Getting started with Lists
FUNCTIONS AND PROCEDURES | Breaking your code into logical sections
FORMATTING DATA | Further data manipulation
ERROR CHECKING | Using Try and Except to catch user errors
OBJECT ORIENTED PROGRAMMING | Getting to grips with OOP
Picture
SUGGESTIONS
We would love to hear from you
SUBSCRIBE 
To enjoy more benefits
We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.