Working with strings

Introduction to Python for Developers

George Boorman

Curriculum Manager, DataCamp

Strings are everywhere!

Ball of strings

 

  • User profiles

 

  • Search engines

 

  • Large language models
1 https://unsplash.com/@steve_j
Introduction to Python for Developers

Python knows single and double quotes

# This works
my_text = 'Hello, my name is George.'

# This also works
my_text = "Hello, my name is George."
  • ' = apostrophe = single quote
Introduction to Python for Developers

Advantages of double quotes

# Single quote string variable containing an apostrophe
my_text = 'Hello, my name's George.'
SyntaxError: invalid syntax.
# Double quote string variable containing an apostrophe
my_text = "Hello, my name's George."
print(my_text)
Hello, my name's George.
Introduction to Python for Developers

Methods

  • Method = a function that is only available to a specific data type

  • str methods

# Calling a string method
str_variable.method()
Introduction to Python for Developers

Replacing parts of strings

  • .replace(text_to_be_replaced, text_to_change_it_to)
my_text = "Hello, my name's George."

# Replace George with John
my_text = my_text.replace("George", "John")

print(my_text)
Hello, my name's John.
  • Common use cases
    • Reformatting e.g., change spaces to underscores
    • Fixing or removing typos
Introduction to Python for Developers

Changing case

current_top_album = "For All The Dogs"


# Convert to lowercase current_top_album = current_top_album.lower() print(current_top_album)
for all the dogs
# Change to upppercase
current_top_album = current_top_album.upper()
print(current_top_album)
FOR ALL THE DOGS
Introduction to Python for Developers

Sentences and paragraphs

nineteen_eightyfour = "It was a bright cold day in April, and the clocks were striking thirteen."
Introduction to Python for Developers

Multi-line strings

# Create a string variable over multiple lines
harry_potter = """Mr. and Mrs. Dursley, 
of number four Privet Drive, 
were proud to say that they were perfectly normal, 
thank you very much.
"""
  • """text""": Multi-line strings
    • Enhance readability
    • Avoid the need to use special characters
    • Longer text such as customer reviews
    • Used to describe what functions do
Introduction to Python for Developers

String cheat sheet

Syntax Purpose Example
Single quotes '' String variable my_string = 'My string'
Double quotes "" String variable my_string = "My string"
Triple quotes """""" Multi-line string variable my_string = """My string"""
str.replace() Replacing parts of strings my_string = my_string.replace("text_to_remove", "text_to_change_to")
str.lower() Lowercase string my_string = my_string.lower()
str.upper() Uppercase string my_string = my_string.upper()
1 https://docs.python.org/3/library/stdtypes.html#string-methods
Introduction to Python for Developers

Let's practice!

Introduction to Python for Developers

Preparing Video For Download...