Since the
str
class is immutable in Python, no method of thestr
class is in-place. Instead, all methods of thestr
class returns a new copy of string.\
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"
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")
"a b".find("A")
Concatenate Strings¶
"Hello, " + "World"
" ".join(["hello", "world"])
Repeat a String¶
"code" * 3
String <-> Numbers¶
"12ab".isdigit()
list(map(lambda x: x.isdigit(), "12ab"))
list(map(lambda x: int(x), "123456789"))
Sliding Windows¶
s = "0123456789"
[s[i : i + 3] for i in range(len(s))]
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),
)
)
String Comparison¶
"/" < "-"
"/" > "-"
count¶
"abc".count("a")
"abca".count("a")
encode¶
"\n".encode("utf-8")
partition¶
s = 'It is "a" good "day" today "a".'
s
s.partition('"a"')
s[0:0]
len(s)
s[31:31]
Notice that
str.split
returns a list rather than a generator.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(" ")
String Prefixes¶
b
,r
,u
andf
are supported prefixes for strings in Python. Notice that prefixesf
andr
can be used together.
b"nima"
x = 1
x
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.