Show Menu
Cheatography

Python Strings Cheat Sheet by

python

Python Strings

Operations on strings and examples:
Mult­iline strings
x = "­"­" This is a
multiline string­"­"­"
Get the character at a specific position
x = "­Python Progra­mmi­ng"
print(­x[1])    ­#print character at position 1
>>> y
Slic­ing
x = "­Python Progra­mmi­ng"
print(­x[3:5])
>>> ho
Negative Indexing
x = "­Python Progra­mmi­ng"
print(­x[-­15:­-13])
>>> ho
String Length
x = "­Hel­lo"
print(­len(x))
>>> 5
Remove any whitespace from the beginning or the end
x = "­    Hello     "
print(­x.s­trip())     #return "­Hel­lo"
Return the string in lower case
x = Hello
print(­x.l­ower())     #return "­hel­lo"
 

Python Strings

Return the string in upper case
x = Hello
print(­x.u­pper())     #return "­HEL­LO"
Replace a string with another string
x = "­Hel­lo"
print(­x.r­epl­ace­("He­"­,"A"))  ­  #return "­All­o"
Choose a separator and split string into substr­ings
x = "­Python Progra­mmi­ng"
print(­x.s­pli­t(" ")) # return ['Python' , 'Progr­amm­ing']
Check if a string is present in a text
txt = "­Tunisia is a North African countr­y"
x = "­Nor­th" in txt
print(x) # return True
Conc­ate­nat­ion
x = "­Hel­lo"
y = "­Wor­ld"
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 {} dollar­s."
print(myorder.format(quantity, itemno, price))
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter

          More Cheat Sheets by Nouha_Thabet