3 Data Types and Numbers
3 Data Types and Numbers
TYPES, NUMBERS
AND CASTING
At the end of this lesson…
You can get the data type of any object by using the type()
function.
Setting the Data Type
Example:
x = 1 # int
y = 2.8 # float
z = 1j # complex
Example
Import the random module, and display a random number
between 1 and 9:
Python Casting
Specify a Variable Type
Example
Get the characters from position 2 to position 5 (not included):
Slice From the Start
• By leaving out the start index, the range will start at the first
character.
Slice To the End
• By leaving out the end index, the range will go to the end:
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters from position 5 to position 1 (not included), starting the
count from the end of the string:
String Concatenation
You can use index numbers {0} to be sure the arguments are placed
in the correct placeholders:
Format String
VS
Escape Character
String Length
Example
The len() function returns the length of a string:
String Methods
Example:
String Methods