This document provides a cheat sheet on Python strings with examples of common string operations like accessing characters, slicing, checking for substrings, concatenation, formatting and changing case. It lists methods for working with strings like upper(), lower(), strip(), split(), replace() and len(). Examples demonstrate slicing characters from indices, negative indexing, checking for substrings with "in", concatenating with +, and inserting values into strings with format().
This document provides a cheat sheet on Python strings with examples of common string operations like accessing characters, slicing, checking for substrings, concatenation, formatting and changing case. It lists methods for working with strings like upper(), lower(), strip(), split(), replace() and len(). Examples demonstrate slicing characters from indices, negative indexing, checking for substrings with "in", concatenating with +, and inserting values into strings with format().
by Nouha_Thabet via cheatography.com/103894/cs/21332/
Python Strings Python Strings
Operations on strings and examples: Return the string in upper case
Multiline strings x = Hello x = """ This is a print(x.upper()) #return "HELLO"
multiline string""" Replace a string with another string
Get the character at a specific position x = "Hello" x = "Python Programming" print(x.replace("He","A")) #return "Allo" print(x[1]) #print character at position 1 Choose a separator and split string into substrings >>> y x = "Python Programming" Slicing print(x.split(" ")) # return ['Python' , 'Progr‐ x = "Python Programming" amming'] print(x[3:5]) Check if a string is present in a text >>> ho txt = "Tunisia is a North African country" Negative Indexing x = "North" in txt x = "Python Programming" print(x) # return True print(x[-15:-13]) Concatenation >>> ho x = "Hello" String Length y = "World" x = "Hello" 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.strip()) #return "Hello" price = 49.95 myorder = "I want {} pieces of item {} for {} Return the string in lower case dollars." x = Hello print(myorder.format(quantity, itemno, price)) print(x.lower()) #return "hello"
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