Learning Python

6. Strings

In Python strings are surrounds by either single quotation marks, or double quotation marks. PEP 8 describes no standard on how to use single or double-quotes:

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257.

Some tools like Black have a preference to have all strings and comments in double quotes, but both ways are correct.

6.1. The basics about strings

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

#!/usr/bin/env python3

def main():
    print("Hello World.")


if __name__ == "__main__":
    main()

Output:

Hello World.

The second form is to assign a variable to a string and can be used by print() as a reference to the string.

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

Hello World.

As seen in the Variables section, variables can be joined with the +-sign and a string can also be concatenated with a variable.

#!/usr/bin/env python3

def main():
    phrase_one = "Hello World."
    phrase_two = "And Goodbye."
    # Concatenate two variables
    print(phrase_one + phrase_two)
    # Concatenate two variables with a string
    print(phrase_one + " " + phrase_two)


if __name__ == "__main__":
    main()

Output:

Hello World.And Goodbye.
Hello World. And Goodbye.

Strings can also be a multiline string with a newline character as part of the value. Python does take the indentation of a multiline string not into account and will the indentation will be part of the string. On Stack Overflow in question 2504411 possible solutions to work around this issue are discusses.

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

Hello World.
    And Goodbye.

6.2. Strings are arrays

Strings are like in other languages arrays and can be address in that way. The working of arrays is described in Arrays, but for now we read the second element of the array and print it.

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

e

As a strings is an array you can easily loop over all elements and get every element separately.

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

H
e
l
l
o

W
o
r
l
d
.

6.3. String length

The built-in function len() return the length of an object and used the internal method __len__() of the object to determine the length.

#!/usr/bin/env python3

def main():
    phrase_one = "Hello World."
    # Using the built-in version
    print(len(phrase_one))
    # Using the internal method of an object
    print(phrase_one.__len__())


if __name__ == "__main__":
    main()
12
12

6.4. Checking a string

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

True
#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

Yes, Hello World.
#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

No, Hello World.

6.5. Slicing strings

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

llo
#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

Hello
#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

llo World.
#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

orl

6.6. Convert your string to upper or lower case

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

HELLO WORLD.
#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

hello world.

6.7. Trim a string

The method strip() removes by default whitespace character from the string on both sides. With lstrip() or rstrip() the string is only being trimmed on the left or ride side.

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

 Hello World.
Hello World.

The method strip by default trims whitespace characters, but can also use other characters to trim a string.

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

o Wor

6.8. Replacing a string

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

Hello world.

6.9. Split and join

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

['Hello', 'World.']
#!/usr/bin/env python3

def main():
    phrases = ["Hello", "World."]
    separator = " "
    print(separator.join(phrases))


if __name__ == "__main__":
    main()

Output:

Hello World.
#!/usr/bin/env python3

def main():
    phrases = {"wordOne": "Hello", "wordTwo": "World."}
    separator = "-"
    print(separator.join(phrases))


if __name__ == "__main__":
    main()

Output:

wordOne-wordTwo

6.10. Formatting strings

#!/usr/bin/env python3

def main():
    name_one = "World"
    phrase_one = "Hello {}."
    print(phrase_one.format(name_one))


if __name__ == "__main__":
    main()

Output:

Hello World.
#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

Hello Jack and John.
#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

Hello John and Jack.

6.11. Escape characters

#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

  File "/workspaces/learning-python/example.py", line 4
    phrase_one = "Hello "World"."
                         ^
SyntaxError: invalid syntax
#!/usr/bin/env python3

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


if __name__ == "__main__":
    main()

Output:

Hello "World".
Code Result
\’ Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value