Skip to content

Strings

Strings in Python are immutable sequences of characters. Almost every operation that modifies a string creates a new string.

So the time complexity of string most operations is O(n) where n is the length of the string. This includes concatenation, slicing, and other operations that create new strings.

"Hello, World!"
'Hello, World!'

Defining a string

text = "Hello, World!"

Trying to concatenate a string with an integer

1
2
3
4
try:
    text + 20
except Exception as error:
    print("Got error:", error)
Got error: can only concatenate str (not "int") to str

f-strings

 f"Just came to say: {text}"
'Just came to say: Hello, World!'

.format

"Just came to say: {text}".format(text=text)
'Just came to say: Hello, World!'

Checking if a string is numeric

"123".isnumeric(), "abc".isnumeric()
(True, False)

Splitting a string

text.split()
['Hello,', 'World!']

Joining a text

"".join(text)
'Hello, World!'

Accessing characters in a string

text[2]
'l'

String are immutable

1
2
3
4
try:
    text[2] = "x"
except Exception as error:
    print("Got an error: ", error)
Got an error:  'str' object does not support item assignment