Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Python Strings Cheat Sheet

by Nouha_Thabet via cheatography.com/103894/cs/21332/

Python Strings Python Strings

Operations on strings and examples: Return the string in upper case


Mult​iline strings x = Hello
x = "​"​" This is a print(​x.u​pper()) #return "​HEL​LO"

multiline string​"​"​" Replace a string with another string


Get the character at a specific position x = "​Hel​lo"
x = "​Python Progra​mmi​ng" print(​x.r​epl​ace​("He​"​,"A")) ​ #return "​All​o"
print(​x[1]) ​#print character at position 1 Choose a separator and split string into substr​ings
>>> y x = "​Python Progra​mmi​ng"
Slic​ing print(​x.s​pli​t(" ")) # return ['Python' , 'Progr​‐
x = "​Python Progra​mmi​ng" amm​ing']
print(​x[3:5]) Check if a string is present in a text
>>> ho txt = "​Tunisia is a North African countr​y"
Negative Indexing x = "​Nor​th" in txt
x = "​Python Progra​mmi​ng" print(x) # return True
print(​x[-​15:​-13]) Conc​ate​nat​ion
>>> ho x = "​Hel​lo"
String Length y = "​Wor​ld"
x = "​Hel​lo" z = x + " " + y
print(​len(x)) print(z) # return "​Hello World"
>>> 5 Insert numbers into strings
Remove any whitespace from the beginning or the end quantity = 3
x = "​ Hello " itemno = 567
print(​x.s​trip()) #return "​Hel​lo" price = 49.95
myorder = "I want {} pieces of item {} for {}
Return the string in lower case
dollar​s."
x = Hello
print(myorder.format(quantity, itemno, price))
print(​x.l​ower()) #return "​hel​lo"

By Nouha_Thabet Published 7th December, 2019. Sponsored by Readable.com


cheatography.com/nouha- Last updated 6th December, 2019. Measure your website readability!
thabet/ Page 1 of 1. https://readable.com

You might also like