Python Basics - Strings Cheat Sheet
by Mario (mariofreitas) via cheatography.com/42813/cs/13207/
String Syntax String Formatting - Printf Arguments
s1 = "this is Strings can be declared with " "... d Int
"
f Float
s2 = 'a ... or ' '
s String
string'
10d Reserves 10 spaces to the int
s1 + s2 Returns s1 concatenated with s2 ('this is a string')
^10d Reserves 10 spaces to the int and centralize the content
s1 * 3 Returns s1 concatenated with itself 3 times (this is
<10d Reserves 10 spaces to the int and align the content left
this is this is)
s1[3] Returns 4th element of s1 (s) >10d Reserves 10 spaces to the int and align the content right
s1[0:3] Returns 1st to 3rd element of s1 (thi) *^10d Reserves 10 spaces to the int , centralize the content and fill
the empty spaces with *
s1[0:7:2] Returns 1st to 7th element of s1 skipping one at a
time (ti s) 0>10d Reserves 10 spaces to the int , align the content right and fill
the empty spaces with 0s
String Methods 0>.2f Format float with 2 decimal places
s = "stRing" 0>10.2f Reserves 10 spaces to the float and format with 2 decimal
places
s.capitalize() Returns capitalized version of s (String)
s.upper() Returns upper case version of s (STRING) String - The format() Method
s.lower() Returns lower case version of s (string) a = 10
s.title() Returns s with first letter of each word b = 3.5555
capitalized (String) print("The value of a is {} and the value of b is
s.swapcase() Returns the case swapped version of s {:.2f}".format(a, b))
(STrING)
Instead of using a formatted string (only available on Python 3.6 and up)
s.replace('tR', 'l') Returns a copy of s with all 'tR' replaced by you can also use the format method inserting .format() at the end of the
'l' (sling) string.
s.startswith('R') Returns true if s starts with 'R' and false
otherwise (False) String Formatting - Example
s.endswith('ing') Returns true if s ends with 'ing' and false a = 10.12571
otherwise (True)
print(f"The value of a is {a:.2f}")
s.split('R') Splits the string into a list of strings. In this
# This code prints "The value of a is 10.13"
case, "R" is the splitting parameter. (["sr",
# Use f before starting a string to make it a
"ing"])
formatted string
s.strip() Removes spaces in the begining and in the
# Use {a} in a formatted string to interpolate the
end of the string ("stRing")
variable a in the string
s.strip("g") Removes "g" in the begining and in the end
# Use :.2f after the variable name to format it as a
of the string ("stRin")
float with 2 decimal places
''.join([s, 's are Returns the string '' concatenated with s and
cool']) 's are cool' ('stRings are cool')
By Mario (mariofreitas) Not published yet. Sponsored by CrosswordCheats.com
cheatography.com/mariofreitas/ Last updated 21st October, 2017. Learn to solve cryptic crosswords!
github.com/MarioRaul/ Page 1 of 1. http://crosswordcheats.com