Cheatography
https://cheatography.com
Python Comments
Example 1 #This is a comment
|
Example 2 #This is a comment #written in #more than just one line
|
Example 3 """ This is a comment written in more than just one line """
|
Python Variables
x = "How old are you ?" #x is of type str print(x) >>> How old are you ? x = 25 #x now is of type int print(x) >>> 25
|
Python Data Types
Text Type: |
|
Numeric Types: |
|
Sequence Types: |
|
Mapping Type: |
|
Set Types: |
|
Boolean Type: |
|
Binary Types: |
bytes, bytearray, memoryview
|
Get the data type of a variable "var" |
|
Python Data Types Examples
Example |
Data Type |
|
|
|
|
|
|
|
|
x = ["Blue","Red","Yellow"]
|
|
x = ("Blue","Red","Yellow")
|
|
|
|
x={"Age":25,"Height":1.72}
|
|
|
|
x = frozenset({"Pink","Red"})
|
|
|
|
|
|
|
|
x = memoryview(bytes(8))
|
|
Get the data type of x : |
x = "Color" print(type(x)) >>> str
|
|
|
Python Casting
Casting is used to specify a type on to a variable and this is done using constructor functions. Examples x = int(5)
#x = 5 x = int(2.8)
#x = 2 x = float(5)
#x = 5.0 x = float(2.8)
#x = 2.8 |
Python Strings
Operations on strings and examples: |
Multiline strings |
x = """ This is a multiline string"""
|
Get the character at a specific position |
x = "Python Programming" print(x[1]) #print character at position 1 >>> y
|
Slicing |
x = "Python Programming" print(x[3:5]) >>> ho
|
Negative Indexing |
x = "Python Programming" print(x[-15:-13]) >>> ho
|
String Length |
x = "Hello" print(len(x)) >>> 5
|
Remove any whitespace from the beginning or the end |
x = " Hello " print(x.strip()) #return "Hello"
|
Return the string in lower case |
x = Hello print(x.lower()) #return "hello"
|
Python Strings
Return the string in upper case |
x = Hello print(x.upper()) #return "HELLO"
|
Replace a string with another string |
x = "Hello" print(x.replace("He","A")) #return "Allo"
|
Choose a separator and split string into substrings |
x = "Python Programming" print(x.split(" ")) # return ['Python' , 'Programming']
|
Check if a string is present in a text |
txt = "Tunisia is a North African country" x = "North" in txt print(x) # return True
|
Concatenation |
x = "Hello" y = "World" z = x + " " + y print(z) # return "Hello World"
|
Insert numbers into strings |
quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price))
|
|
Created By
Metadata
Favourited By
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets
More Cheat Sheets by Nouha_Thabet