Python Strings Cheat Sheet

Posted by

I created a cheat sheet to help when working with common python data types like dictionaries, lists, strings, and tuples.  Knowing how to work with these data types will accelerate your Python development skillset.  I hope you find this useful.

Create Strings

#option1 
bird1 = 'cardinal'

#option2
bird2 = "bluejay"

#option3 - multiline string
bird3 = """ mocking
            bird """

Access characters within a string

bird1 = 'cardinal'

##Access and print the d in cardinal##
print(bird1[3])    

output: d


##Print each char in a string##
for b in bird1:
    print(b)
        
    output: c
            a
            r
            d
            i
            n
            a
            l

Combine a String

bird1 = 'eagle'
bird2 = 'falcon'

##Combine two strings##
birds = bird1 + bird2

Slice existing string and merge with a new string

birds = "eagles, bluejays"
whichbird = "I like " + birds[8:]
print(whichbird)

output: I like bluejays     

Add characters to existing string

birds = "Orioles "
oriole = birds.__add__("are the best!")
print(oriole)

output: Orioles are the best!

Find one or more characters in a string

bird = 'cardinal'
res = bird.__contains__('card')
print(res)

output: True

Return index location of character in a string

bird = 'cardinal'
loc = bird.find('n')
print(loc)

output: 5

Convert different datatypes to strings

##Convert list to string##
hellolst = ['h','i',' ','b','r','e','n','t']
brent = str.join('',hellolst)
print(brent)

output: hi brent
      

##Convert tuple to string##
hellotup = ('hi', ' brent')
brent = str.join('',hellotup)
print(brent)

output: hi brent

I created a simple python program to provide these details as help content in addition to other data types.

https://github.com/RussMaxwell/PythonHelper

Python Cheat Sheet Series

Thank You,

Russ Maxwell