Toggle Menu Icon
Working with Python

Strings

A set of examples working with strings in Python.

String delimiters

You can use single or double quotes to specify a string in Python, this does not change the interpretation of the string like in PHP.

s1 = 'Single quote'
s2 = "Double quote"

Special characters such as \n for new line will be converted:

print('String with a \n new line')
# String with a
#  new line

You can also use triple quotes, either single or double, to span multiple lines:

print("""This string
spans multiple
lines""")
# This string
# spans multiple
# lines

Raw strings

If you want a raw string, not interpreted, prefix the string with r such as:

print(r"This is a raw \n string")
# Output: This is a raw \n string

Concatenate strings

Python is flexible in joining strings, you can use the + operator

s1 = "Hello"
s2 = "World"
s1 + s2
# 'HelloWorld'

You can also use the * operator to repeat a string

s1 = "Repeat"
s1 * 3
# 'RepeatRepeatRepeat'

Join a list of strings

You can join together a list of strings by specifying the glue character(s), this is equivalent to PHP’s implode function:

letters = ['a', 'b', 'c']
print('-'.join(letters))
# Output: a-b-c

Length of String

Use the len() function to get the length of a string (or list).

s = "Test String"
len(s)
# 11

Check for empty string

You can use the len() function to check if a string is empty, 0 length. A slightly easier way to check if a string is empty is to use it as the expression, an empty string will return false.

if not a:
    print("Empty")

# Output: Empty

Check if string exists

Python does not have a contains method, instead you can use in to check if a string contains a substring:

s = "The dog has brown spots"
if "brown" in s:
    print("Yes")

# Output:  Yes

You can also use not in to check if a string does not contain a substring:

s = "The dog has brown spots"
if "black" not in s:
    print("No pink spots")

# Output:  No pink spots

You can also use the .find() method which will return the index of where the substring is located in the string. If only doing a boolean check I’ll just use in since it’s the same for list elements too.

s = "The dog has brown spots"
idx = s.find("brown")
if idx >= 0:
    print(f"Found at position: {idx}")

# Output:  Found at position: 12

String methods

The Python string type has a set of methods defined, see stdtype string methods for full documentation.

💡 Note: To use these methods, they apply to a string type like "this is my string".method() or with your string assigned to a variable svar.method().

Split strings

Python split string on a specific character or word.

s = "a-b-c"
s.split("-")
# ['a', 'b', 'c']

String replace

Python string replace use .replace("this", "that"):

s = "The quick brown fox jumped over the lazy dog"
s.replace("fox", "cat")
# 'The quick brown cat jumped over the lazy dog'

Strip characters

To strip characters from a string in Python, use .strip() if you don’t specify any characters it will use whitespace by default, this includes newlines.

' This is my string \n'.strip()
# 'This is my string'

To specify your own characters to strip, use .strip("rs")

"srabcdefsrs".strip("rs")
# 'abcdef'

There are similar functions, .lstrip() and .rstrip() for left and right strip.

String prefix or suffix

To determine if a string contains a certain prefix or suffix, use .startswith() or .endswith()

s = "prevention"
s.startswith("pre")
# True
s.endswith("tion")
# True
s.startswith("tion")
# False

Resources