This is a draft cheat sheet. It is a work in progress and is not finished yet.
String Syntax
|
Strings can be declared with " "... |
|
... or ' ' |
|
Returns s1 concatenated with s2 ('this is a string') |
|
Returns s1 concatenated with itself 3 times (this is this is this is) |
|
Returns 4th element of s1 (s) |
|
Returns 1st to 3rd element of s1 (thi) |
|
Returns 1st to 7th element of s1 skipping one at a time (ti s) |
String Methods
|
|
Returns capitalized version of s (String) |
|
Returns upper case version of s (STRING) |
|
Returns lower case version of s (string) |
|
Returns s with first letter of each word capitalized (String) |
|
Returns the case swapped version of s (STrING) |
|
Returns a copy of s with all 'tR' replaced by 'l' (sling) |
|
Returns true if s starts with 'R' and false otherwise (False) |
|
Returns true if s ends with 'ing' and false otherwise (True) |
|
Splits the string into a list of strings. In this case, "R" is the splitting parameter. (["sr", "ing"]) |
|
Removes spaces in the begining and in the end of the string ("stRing") |
|
Removes "g" in the begining and in the end of the string ("stRin") |
''.join([s, 's are cool'])
|
Returns the string '' concatenated with s and 's are cool' ('stRings are cool') |
String Formatting - Printf Arguments
|
Int |
|
Float |
|
String |
|
Reserves 10 spaces to the int |
|
Reserves 10 spaces to the int and centralize the content |
|
Reserves 10 spaces to the int and align the content left |
|
Reserves 10 spaces to the int and align the content right |
|
Reserves 10 spaces to the int , centralize the content and fill the empty spaces with * |
|
Reserves 10 spaces to the int , align the content right and fill the empty spaces with 0s |
|
Format float with 2 decimal places |
|
Reserves 10 spaces to the float and format with 2 decimal places |
String - The format() Method
a = 10
b = 3.5555
print("The value of a is {} and the value of b is {:.2f}".format(a, b))
|
Instead of using a formatted string (only available on Python 3.6 and up) you can also use the format method inserting .format() at the end of the string.
String Formatting - Example
a = 10.12571
print(f"The value of a is {a:.2f}")
# This code prints "The value of a is 10.13"
# Use f before starting a string to make it a formatted string
# Use {a} in a formatted string to interpolate the variable a in the string
# Use :.2f after the variable name to format it as a float with 2 decimal places
|
|
|
|