Learning Python

Working with strings

The basics about strings

The most basic form of a string is one that is given directly to the print()

def main:
    print("Hello World.")

Output:

Hello World.
def main:
    phrase_one = "Hello World."
    print(phrase)

Output:

Hello World.
def main:
    phrase_one = "Hello World."
    phrase_two = "And Goodbye."
    print(phrase_one + phrase_two)

Output:

Hello World.And Goodbye.
def main:
    phrase_one = "Hello World."
    phrase_two = "And Goodbye."
    print(phrase_one + " " + phrase_two)

Output:

Hello World. And Goodbye.
def main:
    phrase_one = """Hello World.
    And Goodbye."""
    print(phrase_one)

Output:

Hello World.
And Goodbye.

Strings are arrays

def main:
    phrase_one = "Hello World."
    print(phrase_one[1])

Looping through a string

def main:
    for x in "Hello World.":
        print(x)

String length

def main:
    phrase_one = "Hello World."
    print(len(phrase_one))

Checking a string

def main:
    phrase_one = "Hello World."
    print("Hello" in phrase_one)
def main:
    phrase_one = "Hello World."
    if "Hello" in phrase_one:
        print("Yes, Hello World.")
def main:
    phrase_one = "Hello World."
    if "Hello" not in phrase_one:
        print("Yes, Hello World.")

Slicing strings

def main:
    phrase_one = "Hello World."
    print(phrase_one[2:5])
def main:
    phrase_one = "Hello World."
    print(phrase_one[:5])
def main:
    phrase_one = "Hello World."
    print(phrase_one[2:])
def main:
    phrase_one = "Hello World."
    print(phrase_one[-5:-2])

Modifying strings

Convert your string to upper or lower case

def main:
    phrase_one = "Hello World."
    print(phrase_one.upper())
def main:
    phrase_one = "Hello World."
    print(phrase_one.lower())

Removing a whitespace

def main:
    phrase_one = "Hello World. "
    print(phrase_one.strip())

lstrip and rstrip

Replacing a string

def main:
    phrase_one = "Hello World."
    print(phrase_one.replace("W", "w"))

Split a string

def main:
    phrase_one = "Hello World."
    print(phrase_one.split(" "))

join

Formatting strings

def main:
    name_one = "World"
    phrase_one = "Hello {}."
    print(phrase_one.format(name_one))
def main:
    name_one = "Jack"
    name_two = "John"
    phrase_one = "Hello {} and {}."
    print(phrase_one.format(name_one, name_two))
def main:
    name_one = "Jack"
    name_two = "John"
    phrase_one = "Hello {1} and {0}."
    print(phrase_one.format(name_one, name_two))

Escape characters

def main:
    phrase_one = "Hello "World"."
    print(phrase_one)
def main:
    phrase_one = "Hello \"World\"."
    print(phrase_one)
Code Result
\’ Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value