Ben Chuanlong Du's Blog

It is never too late to learn.

String in Python

  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.

In [4]:
"a" in "a b"
Out[4]:
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.

In [5]:
"a b".find("a")
Out[5]:
0
In [6]:
"a b".find("A")
Out[6]:
-1

Concatenate Strings

In [13]:
"Hello, " + "World"
Out[13]:
'Hello, World'
In [15]:
" ".join(["hello", "world"])
Out[15]:
'hello world'

Repeat a String

In [16]:
"code" * 3
Out[16]:
'codecodecode'

String <-> Numbers

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

Sliding Windows

In [4]:
s = "0123456789"
[s[i : i + 3] for i in range(len(s))]
Out[4]:
['012', '123', '234', '345', '456', '567', '678', '789', '89', '9']
In [8]:
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),
    )
)
Out[8]:
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j']]

String Comparison

In [1]:
"/" < "-"
Out[1]:
False
In [2]:
"/" > "-"
Out[2]:
True

count

In [1]:
"abc".count("a")
Out[1]:
1
In [2]:
"abca".count("a")
Out[2]:
2

encode

In [1]:
"\n".encode("utf-8")
Out[1]:
b'\n'

partition

In [2]:
s = 'It is "a" good "day" today "a".'
s
Out[2]:
'It is "a" good "day" today "a".'
In [4]:
s.partition('"a"')
Out[4]:
('It is ', '"a"', ' good "day" today "a".')
In [5]:
s[0:0]
Out[5]:
''
In [6]:
len(s)
Out[6]:
31
In [7]:
s[31:31]
Out[7]:
''
  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 .

In [1]:
"how are you".split(" ")
Out[1]:
['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.
In [1]:
b"nima"
Out[1]:
b'nima'
In [2]:
x = 1
In [7]:
x
Out[7]:
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.

Comments