In the last class we talked about variables and we said variable data type is whatever values are assigned to the variable. Python does have various data types and data type is an important concept in any programming language. Variables can store data of different types, and different data types can do different things.
Python Data Types:
- Text Type: str
- Numeric Types: int, float, complex
- Sequence Types: list, tuple, range
- Mapping Type: dict
- Set Types: set, frozenset
- Boolean Type: bool
- Binary Types: bytes, bytearray, memoryview
- None Type: NoneType
And as we also learnt in the last class, to get the data type of any variable/object one can use the in-built type() function:
x = 5
print(type(x))
Let's take a look at some of this data types
1. Numbers
Numbers Include:
- int
- float
- complex
example:
a = 9 # int
b = 52.1 # float
c = 7j # complex
print (a);
print (b);
print (c);
Int: Int, or integer, is a positive or negative whole number of unlimited length.
Example
a = 2
b = 653243262112
c = -7456
print(type(a))
print(type(b))
print(type(c))
Float: Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Example
a = 6.20
b = 4.0
c = -21.78
print(type(a))
print(type(b))
print(type(c))
Complex: Complex numbers are written with a 'j' as the imaginary part:
Example
a = 6+5j
b = 2j
c = -8j
print(type(a))
print(type(b))
print(type(c))
Random Number
Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers, but to do that you have to import the python 'random'
Example
import random
print(random.randrange(101, 999))
2. Booleans
Booleans represent one of two values: True or False.
Example
print(16 > 9)
print(4 == 9)
print(21 < 9)
When you run a condition in an if statement, Python returns True or False:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Evaluate Values and Variables
The bool() function is use to evaluate any value, and returns True or False;
- All value is evaluated to True if it has content.
- Any string is True, except empty strings.
- Any number is True, except 0.
- Any list, tuple, set, and dictionary are True, except empty ones.
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
print(bool(["apple", "cherry", "banana"]))
Note that function can also return Boolean:
Example
def myFunction() :
return True
print(myFunction())
3. String
Like we have learnt about string earlier, strings are surrounded by either single quotation, double quotation, or triple quotation.
Note: when using triple quotation, in the result, the line breaks are inserted at the same position as in the code.
Are Strings Arrays?
Sure they are, just like other programing language string in python are simple arrays of characters. Python does not have character data type like other languages so a character is simply a string with length of 1.
Example: Get the character at position 3 (remember first character is at position 0):
name = "Peter Agbo"
print(name[3])
As string is an array, one can definitely loop through the characters of a string with a for loop
name = "Peter Agbo"
for x in name:
print(x)
(we will learn more about loop statements later)
- To get the length of a string use len():
name = "Peter Agbo"
print(len(name))
- To check if a phrase or character exist in string use 'in':
txt = "I love programming python!"
print("love" in txt)
- To check if a phrase or character do not exist in string use 'not in':
txt = "I love programming python!"
print("php" not in txt)
String Slicing
Treating string as array, one can use the square bracket to get a range of characters in a string (this is called slice). Specify the start and end index separated by a colon.
txt = "I love programming python!"
print(txt[3 : 7])
Note: The first character has index 0.
To slice from the start leave the start index empty
txt = "I love programming python!"
print(txt[ : 7])
To slice to the end leave the end index empty
txt = "I love programming python!"
print(txt[5 : ])
Negative Indexing: Use negative indexes to start the slice from the end of the string:
txt = "I love programming python!"
print(txt[-7 : -3])
Modify Strings
- Upper Case: upper()
txt = "I love programming python!"
print(txt.upper())
- Lower Case: lower()
txt = "I love programming python!"
print(txt.lower())
- Remove Whitespace (the space before and/or after the actual text): strip()
txt = " I love programming python! "
print(txt.strip())
- Replace String: replace()
txt = "I love programming python!"
print(txt.replace("p", "j"))
- Split String (method splits the string into substrings if it finds instances of the separator and return a list): split()
txt = "I love programming python!"
print(txt.split(","))
String Concatenation
The + operator is use to combine or concatenate two strings
name = "Abdulmutalib"
skill = "Python"
details = name + " loves to coding " + skill
print (details)
Format Strings
Note: concatenation will not work for combining string with any other variable of different data type.
That mean the following code will result in an error
name = "Abdulmutalib"
age = 36
details = name + " is " + age
print (details)
The right way to handle this will be to use the in-built method format() to format the integer 'age' and your combine it with name
name = "Abdulmutalib"
age = 36
details = name + " is {}"
print (details.format(age))
The format() method can takes unlimited number of arguments, and are placed into the respective placeholders:
name = "Abdulmutalib"
age = 36
skill = "Python"
years = 5
details = name + " is {} and has been coding in " + skill + " for {} years"
print (details.format(age, years))
Furthermore the placeholders can be assigned index numbers to make sure they are place in the right placeholders
name = "Abdulmutalib"
age = 36
skill = "Python"
years = 5
details = name + " is {1} and has been coding in " + skill + " for {0} years"
print (details.format(years, age))
Escape Character
To use characters that are alien to string in python you need to use and escape character, which is backslash \
For example if you do the follow in python you will get invalid syntax error
txt = "I am the king in the "North" right now";
print (txt)
The best way will be to apply the escape character to the two double quote ("} inside the string like this
txt = "I am the king in the \"North\" right now";
print (txt)
Other places one need to apply the escape character are:
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
we will study most of them as we progress
String Methods
Python has a set of built-in methods that you can use on strings.
capitalize() Converts the first character to uppercase
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to uppercase
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Comments