Python Basics & Strings Cheat Sheet
by Nouha_Thabet via cheatography.com/103894/cs/21291/
Hello World in Python Python Casting
print("Hello World!") Casting is used to specify a type on to a variable and this is done
using constructor functions.
Python Comments Examples
x = int(5) #x = 5
Example 1
x = int(2.8) #x = 2
#This is a comment
x = float(5) #x = 5.0
Example 2
x = float(2.8) #x = 2.8
#This is a comment
#written in
Python Strings
#more than just one line
Operations on strings and examples:
Example 3
""" This is a comment Multiline strings
written in x = """ This is a
more than just one line """ multiline string"""
Get the character at a specific position
Python Variables
x = "Python Programming"
x = "How old are you ?" #x is of type str print(x[1]) #print character at position 1
print(x) >>> y
>>> How old are you ? Slicing
x = 25 #x now is of type int
x = "Python Programming"
print(x)
print(x[3:5])
>>> 25
>>> ho
Negative Indexing
Python Data Types
x = "Python Programming"
Text Type: str
print(x[-15:-13])
Numeric Types: int, float, complex
>>> ho
Sequence Types: list, tuple, range
String Length
Mapping Type: dict
x = "Hello"
Set Types: set, frozenset print(len(x))
Boolean Type: bool >>> 5
Binary Types: bytes, bytearray, memoryview Remove any whitespace from the beginning or the end
Get the data type of a variable "var" x = " Hello "
print(x.strip()) #return "Hello"
type(var)
Return the string in lower case
Python Data Types Examples x = Hello
print(x.lower()) #return "hello"
Python Strings
Example Data Type Return the string in upper case
x = "Color" list x = Hello
x = 1 int print(x.upper()) #return "HELLO"
x = 1.2 float Replace a string with another string
x = 2j complex x = "Hello"
print(x.replace("He","A")) #return "Allo"
x = ["Blue","Red","Yellow"] list
Choose a separator and split string into substrings
x = ("Blue","Red","Yellow") tuple
x = "Python Programming"
x = range(8) range
print(x.split(" ")) # return ['Python' , 'Progr‐
x={"Age":25,"Height":1.72} dict amming']
x = {"Pink","Red"} set Check if a string is present in a text
x = frozenset({"Pink","Red"}) frozenset txt = "Tunisia is a North African country"
x = True bool x = "North" in txt
x = b"Color" bytes print(x) # return True
x = bytearray(8) bytearray Concatenation
x = memoryview(bytes(8)) memoryview x = "Hello"
y = "World"
Get the data type of x :
z = x + " " + y
x = "Color"
print(z) # return "Hello World"
print(type(x))
Insert numbers into strings
>>> str
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {}
dollars."
print(myorder.format(quantity, itemno, price))
By Nouha_Thabet Published 4th December, 2019. Sponsored by Readable.com
cheatography.com/nouha- Last updated 6th December, 2019. Measure your website readability!
thabet/ Page 1 of 2. https://readable.com