String methods Flashcards

1
Q

Return a copy of the string with its first character capitalized and the rest lowercased.

A

str.capitalize()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does str.center(width[, fillchar]) ?

A

Return centered in a string of length width. Padding is done using the specified fillchar (default is a space).

>>> 'text'.center(10)
>>> 'text'.center(10, '#')
'###text###'
>>> 'text'.center(11, '#')
'####text###'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to count char / substring in str?

A

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to decode / encode?

A

str. decode([encoding[, errors]])
str. encode([encoding[, errors]])

Encodings: ‘utf-8’, ‘ascii’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Check if str ends with given suffix.

A

str.endswith(suffix[, start[, end]]) # returns True or False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to replace \t tabs with given indend size?

A

> > > ‘01\t012\t0123\t01234’.expandtabs() # default is 8
‘01 012 0123 01234’
‘01\t012\t0123\t01234’.expandtabs(4)
‘01 012 0123 01234’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Find substring in the given str.

A

str.find(sub[, start[, end]])

Returns an index of the first substring occurrence. -1 if not found.

To check if sub is a substring or not, don’t use .find, use the in operator:

> > > ‘Py’ in ‘Python’
True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What’s the diff between str.index and str.find methods?

A

They’re almost the same, but index also raises ValueError when the substring is not found. Find returns -1 if nothing found.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to format strings with .format?

A

Args are called by indices. Your kwargs can be **any_dict or keyworded args, they can be called by the keys.

> > > ‘{0} {1} {a}’.format(‘o’, ‘one1’, **{‘a’: ‘a char’})
‘o one1 a char’

> > > ‘{0} {1} {a}’.format(‘o’, ‘one1’, a=’a char’)
‘o one1 a char’

for format tricks see separate deck for it!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to check if there is at least one character and all chars are alphabetic?

A

str.isalpha() # True / False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to check if there is at least one character and all chars are digits?

A

str.isdigit() # True / False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to check if there is at least one character and all chars are lowercase?

A

str.islower() # True / False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to check if there is at least one character and all chars are whitespaces?

A

str.isspace()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to check if there is at least one character and the string is title-cased (first letter in every word is upper-case, all next - lower-case)?

A

str.istitle()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to check if there is at least one character and all chars are uppercase?

A

str.isupper()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Concatenate / build the string from the iterable.

A

separator_str.join(iterable)

> > > l = [‘1’,’2’,’3’]
‘, ‘.join(l)
‘1, 2, 3’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How to get left-justified string?

A

str.ljust(width[, fillchar])
Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than or equal to len(s)

> > > info = {‘name’:’nick’, ‘surname’:’bulow’, ‘age’:’153’}
for k, v in info.items(): print k.ljust(10), v
“age 153
surname bulow
name nick”

brainscape font is not fixed width, so output example is broken. second column should have straight order.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How to get right-justified string?

A

str.rjust(width[, fillchar])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How to convert all str chars to lowercase?

A

str.lower()

20
Q

How to strip given leading and trailing characters from the string?

A

str.strip([chars])

> > > ’ spacious ‘.strip()
‘spacious’
‘www.example.com’.strip(‘cmowz.’)
‘example’

21
Q

How to strip given leading (left side) characters from the string?

A

str.lstrip([chars])

> > > ’ spacious ‘.lstrip()
‘spacious ‘
‘www.example.com’.lstrip(‘cmowz.’)
‘example.com’

22
Q

How to strip given trailing (right side) characters from the string?

A

str.rstrip([chars])

> > > ’ spacious ‘.rstrip()
‘ spacious’
‘mississippi’.rstrip(‘ipz’)
‘mississ’

23
Q

What is the purpose of str.partition(sep) ?

A

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

> > > ‘super-hero’.partition(‘-‘)
(‘super’, ‘-‘, ‘hero’)
‘superhero’.partition(‘-‘)
(‘superhero’, ‘’, ‘’)

24
Q

How to replace chars / substring in the str?

A

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

25
Q

How to find the first occurence of substr starting from the right side in the reverse order?

A

str.rfind(sub[, start[, end]])

26
Q

What’s the diff between str.rindex and str.rfind methods?

A

They’re almost the same, but rindex also raises ValueError when the substring is not found. Rfind returns -1 if nothing found.

27
Q

What is the purpose of str.rpartition(sep) ?

A

Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

28
Q

How to check if there is at least one character and all chars are alphabetic and / or numeric?

A

str.isalnum()

29
Q

How to split lines by the given separator?

A

str.split([sep[, maxsplit]])

30
Q

What if two or more separators stand alongside each other in the string to be split?
like ‘1,,2’.split(‘,’)

A

> > > ‘1,,2’.split(‘,’)
[‘1’, ‘’, ‘2’]
‘1,,,2’.split(‘,’)
[‘1’, ‘’, ‘’, ‘2’]

31
Q

Can split separator contain more than one char?

A

Sure! ‘1<>2<>3’.split(‘<>’) returns [‘1’, ‘2’, ‘3’]

32
Q

What if you split empty str?

A

You get list with empty str obj in it
»> ‘‘.split(‘.’)
[’’]

33
Q

What if no split separator is provided or it is None?

A
A different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
>>> ' 1  2   3  '.split()
['1', '2', '3']
>>> '  1  2   3  '.split(None, 1)
['1', '2   3  '].
34
Q

How to start splitting text moving in right to left order?

A
str.rsplit([sep[, maxsplit]])
# main idea of rsplit is to be used with maxsplit, without it is just split.
35
Q

What is the purpose of str.splitlines

A

str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries (“\r”, “\n”, and “\r\n” are line boundaries).

If keepends is True - save line boundaries char in the output.

> > > ‘ab c\n\nde fg\rkl\r\n’.splitlines()
[‘ab c’, ‘’, ‘de fg’, ‘kl’]
‘ab c\n\nde fg\rkl\r\n’.splitlines(True)
[‘ab c\n’, ‘\n’, ‘de fg\r’, ‘kl\r\n’]

36
Q

Describe diff between split and splitlines.

A

Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

> > > ”“.splitlines()
[]
“One line\n”.splitlines()
[‘One line’]

For comparison, split(‘\n’) gives:
»>

> > > ’‘.split(‘\n’)
[’’]
‘Two lines\n’.split(‘\n’)
[‘Two lines’, ‘’]

37
Q

unicode splitlines

A

unicode splitlines

38
Q

Check if str starts with given suffix.

A

str.startswith(suffix[, start[, end]]) # returns True or False

39
Q

How to swap case?

A

str.swapcase()

40
Q

Return a titlecased version of the string.

A

str.title()
»> “they’re bill’s friends from the UK”.title()
“They’Re Bill’S Friends From The Uk”

41
Q

How to avoid text after apostrophies to be titlecased?

A

> > > import re
def titlecase(s):
… return re.sub(r”[A-Za-z]+(‘[A-Za-z]+)?”,
… lambda mo: mo.group(0)[0].upper() +
… mo.group(0)[1:].lower(),
… s)

titlecase(“they’re bill’s friends.”)

42
Q

What is unicode.splitlines() ?

A

Return a list of the lines in the string, like str.splitlines(). However, the Unicode method splits on the following line boundaries:

Representation 	Description
\n 	Line Feed
\r 	Carriage Return
\r\n 	Carriage Return + Line Feed
\v or \x0b 	Line Tabulation
\f or \x0c 	Form Feed
\x1c 	File Separator
\x1d 	Group Separator
\x1e 	Record Separator
\x85 	Next Line (C1 Control Code)
\u2028 	Line Separator
\u2029 	Paragraph Separator
43
Q

How to update existing chars in the string by the chars from given translation table?

A

Use str.translate(table[, deletechars]). For table creation use helper func from string import maketrans(from, to):

> > > from string import maketrans
table = maketrans(‘aeio’, ‘4310’)
‘hello interesting world’.translate(table)
‘h3ll0 1nt3r3st1ng w0rld’

44
Q

How to convert all str chars to uppercase?

A

str.upper()

45
Q

What is str.zfill?

A

str.zfille(width) # return string filled left with len(str) - width zeros:

> > > ‘test’.zfille(7)
‘000test’

46
Q

unicode.isnumeric() unicode.isdecimal()¶

A

unicode.isnumeric() unicode.isdecimal()¶