Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

  1. Since the str class is immutable in Python, no method of the str class is in-place. Instead, all methods of the str class returns a new copy of string.

  2. \ needs to be escaped (i.e., use \\) in triple quotes.

The in Operator

There is no method named contains in the str class. You can either use the in keyword (preferred) or str.find to perform substring match.

"a" in "a b"
True

You can also use str.find of course. This can be more convenient if you need to use the index where the string is found as well.

"a b".find("a")
0
"a b".find("A")
-1

Concatenate Strings

"Hello, " + "World"
'Hello, World'
" ".join(["hello", "world"])
'hello world'

Repeat a String

"code" * 3
'codecodecode'

String <-> Numbers

"12ab".isdigit()
False
list(map(lambda x: x.isdigit(), "12ab"))
[True, True, False, False]
list(map(lambda x: int(x), "123456789"))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Sliding Windows

s = "0123456789"
[s[i : i + 3] for i in range(len(s))]
['012', '123', '234', '345', '456', '567', '678', '789', '89', '9']
import itertools as it

# sliding using iertools.groupby
s = "abcdefghij"
it.groupby(enumerate(s), lambda e: e[0] // 3)
# to manually see it
list(
    map(
        lambda g: list(map(lambda e: e[1], g[1])),
        it.groupby(enumerate(s), lambda e: e[0] // 3),
    )
)
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j']]

String Comparison

"/" < "-"
False
"/" > "-"
True

count

"abc".count("a")
1
"abca".count("a")
2

encode

"\n".encode("utf-8")
b'\n'

partition

s = 'It is "a" good "day" today "a".'
s
'It is "a" good "day" today "a".'
s.partition('"a"')
('It is ', '"a"', ' good "day" today "a".')
s[0:0]
''
len(s)
31
s[31:31]
''
  1. Notice that str.split returns a list rather than a generator.

  2. str.split removes delimiters when splitting a string. If you want to keep delimiters, you can use lookahead and lookbehind in regular expressions to help you. For more details, please refer to Regular Expression in Python .

"how are you".split(" ")
['how', 'are', 'you']

String Prefixes

  1. b, r, u and f are supported prefixes for strings in Python. Notice that prefixes f and r can be used together.

b"nima"
b'nima'
x = 1
x
1

str.capitalize

The method str.capitalize capitalizes the first letter of a string. The method str.title capitalizes each word.

str.replace

The method str.replace replaces an old string with a new string.