Python - String Methods Flashcards

1
Q

Return - string
Args - none
___________
returns a string with first letter capitalized and all other characters lowercased. It doesn’t modify the original string

A

string.capitalize()

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

Return - string
Args - (width, ‘some char’)
___________
returns a string padded on both sides with specified char. It doesn’t modify the original string. If no second arg provided then blank spaces are default.

A

string.center()

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

Return - string
Args - none
___________
removes all case distinctions present in a string. It is used for caseless matching, i.e. ignores cases when comparing. For example, German lowercase letter ß is equivalent to ss. However, since ß is already lowercase, lower() method does nothing to it. But, casefold() converts it to ss.

A

string.casefold()

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

Return - int
Args - (substring, start, end)
___________
searches the substring in the given string and returns how many times the substring is present in it. It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.

A

string.count()

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

Return - True/False
Args - (suffix, start, end)
___________
returns True if a string ends with the specified suffix. If not, it returns False.

A

string.endswith()

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

Return - copy of string
Args - (tab size)
___________
returns a copy of string with all tab characters ‘\t’ replaced with whitespace characters until the next multiple of tabsize parameter.

A

string.expandtabs()

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

Return - byte string
Args - (encoding=’UTF-8’,errors=’strict’)
___________
By default, encode() method doesn’t require any parameters.

It returns utf-8 encoded version of the string. In case of failure, it raises a UnicodeDecodeError exception.

However, it takes two parameters:

1) encoding - the encoding type a string has to be encoded to
2) errors - response when encoding fails.
There are six types of error response:

strict - default response which raises a UnicodeDecodeError exception on failure

ignore - ignores the unencodable unicode from the result

replace - replaces the unencodable unicode to a question mark ?

xmlcharrefreplace - inserts XML character reference instead of unencodable unicode

backslashreplace - inserts a \uNNNN espace sequence instead of unencodable unicode

namereplace - inserts a \N{…} escape sequence instead of unencodable unicode

A

string.encode()

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

Return - index
Args - (substring, start, end)
___________
returns the index of first occurrence of the substring (if found). If not found, it returns -1. Start and End args are optional.

A

string.find()

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

Return - formatted string with inputs
Args - (first input, second input, …)
___________
reads the type of arguments passed to it and formats it according to the format codes defined in the string. First value in given string is the argument it references and will substitute for in the given parameters, first number after colon is the number of total spaces allocated to the entire inputted argument, number after decimal with the f is the number of decimal places after the input number

A

“blah blah {0} blah blah {1:5.3f}”.format(‘input0’, ‘input2’)

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

Return - index
Args - (substring, start, end)
___________
returns the index of a substring inside the string (if found). If the substring is not found, it raises an exception

A

string.index()

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

Return - True/False
Args - none
___________
returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False

A

string.isalnum()

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

Return - True/False
Args - none
___________
returns True if all characters in the string are alphabets. If not, it returns False.

A

string.isalpha()

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

Return - True/False
Args - none
___________
returns True if all characters in a string are decimal characters. If not, it returns False.

A

string.isdecimal()

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

Return - True/False
Args - none
___________
returns True if all characters in a string are digits. If not, it returns False

A

string.isdigit()

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

Return - True/False
Args - none
___________
returns True if the string is a valid identifier in Python. If not, it returns False.

A

string.isidentifier()

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

Return - True/False
Args - none
___________
returns True if all alphabets in a string are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False.

A

string.islower()

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

Return - True/False
Args - none
___________
returns True if all characters in a string are numeric characters. If not, it returns False.

A

string.isnumeric()

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

Return - True/False
Args - none
___________
returns True if all characters in the string are printable or the string is empty. If not, it returns False.

Characters that occupies printing space on the screen are known as printable characters. For example:

letters and symbols
digits
punctuation
whitespace

A

string.isprintable()

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

Return - True/False
Args - none
___________
returns True if there are only whitespace characters in the string. If not, it return False.

Characters that are used for spacing are called whitespace characters. For example: tabs, spaces, newline etc.

A

string.isspace()

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

Return - True/False
Args - none
___________
returns True if the string is a titlecased string. If not, it returns False.

A

string.istitle()

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

Return - True/False
Args - none
___________
returns whether or not all characters in a string are uppercased or not.

A

string.isupper()

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

Return - concatenated string
Args - (iterable)
___________
provides a flexible way to concatenate string. It concatenates each element of an iterable (such as list, string and tuple) to the string and returns the concatenated string

A

separator = ‘, ‘

separator.join(someIterable)

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

Return - string
Args - (width, ‘optional fill char’)
___________
returns a left or right-justified string of a given minimum width.

A

string.ljust() and rjust()

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

Return - lowercased version of string
Args - none
___________
converts all uppercase characters in a string into lowercase characters and returns it.

A

string.lower()

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

Return - uppercased version of string
Args - none
___________
converts all lowercase characters in a string into uppercase characters and returns it.

A

string.upper()

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

Return - opposite-cased version of string
Args - none
___________
converts all uppercase characters to lowercase and all lowercase characters to uppercase characters of the given string, and returns it.

A

string.swapcase()

27
Q

Return - stripped string
Args - (‘char’) or ([char1, char2, …])
___________
removes characters from the leading left or right based on the argument (a string specifying the set of characters to be removed).

A

string.lstrip() and rstrip()

28
Q

Return - stripped string
Args - (‘char’) or ([char1, char2, …])
___________
removes characters from both left and right based on the argument (a string specifying the set of characters to be removed).

The strip() returns a copy of the string with both leading and trailing characters stripped.

When the combination of characters in the chars argument mismatches the character of the string in the left, it stops removing the leading characters.
Similarly, when the combination of characters in the chars argument mismatches the character of the string in the right, it stops removing the trailing characters.

A

string.strip()

29
Q

Return - 3-tuple
Args - (separator)
___________
splits the string at the first occurrence of the argument string and returns a tuple containing the part the before separator, argument string and the part after the separator.

The partition method returns a 3-tuple containing:

the part before the separator, separator parameter, and the part after the separator if the separator parameter is found in the string
string itself and two empty strings if the separator parameter is not found

A

string.partition()

30
Q

Return - dict
Args - (x, y, z)
___________
returns a mapping table for translation usable for translate() method.

In simple terms, the maketrans() method is a static method that creates a one to one mapping of a character to its translation/replacement.

It creates a Unicode representation of each character for translation.

This translation mapping is then used for replacing a character to its mapped character when used in translate() method.

3 parameters:

x - If only one argument is supplied, it must be a dictionary.
The dictionary should contain 1-to-1 mapping from a single character string to its translation OR a unicode number (97 for ‘a’) to its translation.
y - If two arguments are passed, it must be two strings with equal length.
Each character in the first string is a replacement to its corresponding index in the second string.
z - If three arguments are passed, each character in the third argument is mapped to None.

A

string.maketrans()

31
Q

Return - 3-tuple
Args - (separator)
___________
splits the string at the last occurrence of the argument string and returns a tuple containing the part the before separator, argument string and the part after the separator.

The rpartition method returns a 3-tuple containing:

the part before the separator, separator parameter, and the part after the separator if the separator parameter is found in the string
two empy strings, followed by the string itself if the separator parameter is not found

A

string.rpartition()

32
Q

Return - string
Args - (table)
___________
returns a string where each character is mapped to its corresponding character in the translation table.

The translate() method takes a single parameter:

table - a translation table containing the mapping between two characters; usually created by maketrans()

A

string.translate()

33
Q

Return - string
Args - (old substring, new substring, number of times you want it replaced with)
___________
returns a copy of the string where all occurrences of a substring is replaced with another substring.

A

string.replace()

34
Q

Return - index
Args - (substring, start, end)
___________
returns the highest index of the substring (if found). If not found, it returns -1.

The rfind() method takes maximum of three parameters:

sub - It’s the substring to be searched in the str string.
start and end (optional) - substring is searched within str[start:end]

A

string.rfind()

35
Q

Return - index
Args - (substring, start, end)
___________
returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an exception.

The rindex() method takes three parameters:

sub - substring to be searched in the str string.
start and end(optional) - substring is searched within str[start:end]

A

string.rindex()

36
Q

Return - list of strings
Args - (separator, max # of splits desired)
___________
breaks up a string at the specified separator and returns a list of strings.

The split() method takes maximum of 2 parameters:

separator (optional)- The is a delimiter. The string splits at the specified separator.

If the separator is not specified, any whitespace (space, newline etc.) string is a separator.

maxsplit (optional) - The maxsplit defines the maximum number of splits.

The default value of maxsplit is -1, meaning, no limit on the number of splits.

A

string.split()

37
Q

Return - list of strings
Args - (separator, max # of splits desired)
___________
splits string from the right at the specified separator and returns a list of strings.

The rsplit() method takes maximum of 2 parameters:

separator (optional)- The is a delimiter. The rsplit() method splits string starting from the right at the specified separator.

If the separator is not specified, any whitespace (space, newline etc.) string is a separator.

maxsplit (optional) - The maxsplit defines the maximum number of splits.

The default value of maxsplit is -1, meaning, no limit on the number of splits.

A

string.rsplit()

38
Q

Return - list of strings
Args - (optional keepends=True)
___________
splits the string at line breaks and returns a list of lines in the string.

The splitlines() takes maximum of 1 parameter.

keepends (optional) - If keepends is provided and True, line breaks are also included in items of the list.

A

string.splitlines()

39
Q

Return - boolean
Args - (prefix, start, end)
___________
returns True if a string starts with the specified prefix(string). If not, it returns False.

The startswith() method takes maximum of three parameters:

prefix - String or tuple of strings to be checked
start (optional) - Beginning position where prefix is to be checked within the string.
end (optional) - Ending position where prefix is to be checked within the string.

A

string.startswith()

40
Q

Return - string
Args - none
___________
returns a string with first letter of each word capitalized; a title cased string.

A

string.title()

41
Q

Return - string
Args - (width)
___________
returns a copy of the string with ‘0’ characters padded to the left.

The width specifies the length of the returned string from zfill() with ‘0’ digits filled to the left.

A

string.zfill()

42
Q

Return - string
Args - ( dictionary of mapped key-values )
___________
similar to str.format(mapping) except that str.format(mapping) creates a new dictionary whereas str.format_map(mapping) doesn’t.

A

string.format_map()

43
Q

Return - boolean
Args - ( iterable )
___________
returns True if any element of an iterable is True. If not, any() returns False. If empty, returns returns False.

A

string.any()

44
Q

Return - boolean
Args - ( iterable )
___________
returns True when all elements in the given iterable are true. If not, it returns False. If empty, returns True.

A

string.all()

45
Q

Return - string
Args - ( object like string, list, etc )
___________
returns a string containing a printable representation of an object. It escapes the non-ASCII characters in the string using \x, \u or \U escapes.

A

string.ascii()

46
Q

Return - boolean
Args - ( value )
___________
converts a value to Boolean (True or False) using the standard truth testing procedure.

The following values are considered false in Python:

None

False

Zero of any numeric type. For example, 0, 0.0, 0j

Empty sequence. For example, (), [], ‘’.

Empty mapping. For example, {}

objects of Classes which has __bool__() or __len()__ method which returns 0 or False

All other values except these values are considered true.

A

string.bool()

47
Q

Return - complex #
Args - ( string with real and imag parts )
___________
returns a complex number when real and imaginary parts are provided, or it converts a string to a complex number.

The string passed to the complex() should be in the form real+imagj or real+imagJ

In general, the complex() method takes two parameters:

real - real part. If real is omitted, it defaults to 0.
imag - imaginary part. If imag is omitted, it default to 0.
If the first parameter passed to this method is a string, it will be interpreted as a complex number. In this case, second parameter shouldn’t be passed.

A

string.complex()

48
Q

Return - tuples of (counter, iterable)
Args - ( iterable, optional start value )
___________
adds counter to an iterable and returns it (the enumerate object).

The enumerate() method takes two parameters:

iterable - a sequence, an iterator, or objects that supports iteration
start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.

A

enumerate()

49
Q

Return - an iteratOR
Args - ( function, iterable )
___________
constructs an iterator from elements of an iterable for which a function returns true.

filters the given iterable with the help of a function that tests each element in the iterable to be true or not.

A

filter()

50
Q

Return - float
Args - ( optional string to convert )
___________
returns a floating point number from a number or a string.

The float() method takes a single parameter:

x (Optional) - number or string that needs to be converted to floating point number
If it’s a string, the string should contain decimal points

A

float()

51
Q

Return - string
Args - ( optional string to prompt user )
___________
reads a line from input, converts into a string and returns it.

A

input()

52
Q

Return - int object
Args - ( string to convert, optional base )
___________
returns an integer object from any number or string.

he int() method returns:

an integer object from the given number or string, treats default base as 10
(No parameters) returns 0
(If base given) treats the string in the given base (0, 2, 8, 10, 16)

A

int()

53
Q

Return - iter object
Args - ( set/tuple object to turn into iter, optional sentinel value to represent end of sequence )
___________
creates an object which can be iterated one element at a time.

These objects are useful when coupled with loops like for loop, while loop.

A

iter()

54
Q

Return - length
Args - ( string/bytes/tuple/list/range )
___________
returns the number of items (length) in an object.

A

len()

55
Q

Return - largest element
Args - ( iterable, optional second iterable to compare against one-by-one, etc )
___________
returns the largest element in an iterable or largest of two or more parameters.

A

max()

56
Q

Return - smallest element
Args - ( iterable, optional second iterable to compare against one-by-one, etc )
___________
returns the smallest element in an iterable or smallest of two or more parameters.

A

min()

57
Q

Return - map object
Args - ( function, iterable )
___________
applies a given function to each item of an iterable (list, tuple etc.) and returns a map of the results.

this map can then be wrapped by the list() method to create a list of the results, or wrapped by a set() method, etc

A

map()

58
Q

Return - int representing unicode
Args - ( char )
___________
returns an integer representing Unicode code point for the given Unicode character.

A

ord()

59
Q

Return - sequence
Args - ( tuple/string/list/range )
___________
returns the reversed iterator of the given sequence.

A

reversed()

60
Q

Return - slice object
Args - ( optional start, stop, optional step )
___________
creates a slice object representing the set of indices specified by range(start, stop, step).

The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol (implements __getitem__() and __len__() method).

A

slice()

61
Q

Return - sorted list
Args - ( iterable, optional reverse=True, optional function that serves as a key to the sort comparison )
___________
returns a sorted list from the given iterable.

A

sorted()

62
Q

Return - sum
Args - ( iterable, optional start value )
___________
adds the items of an iterable and returns the sum.

A

sum()

63
Q

Return - iterator of tuples
Args - ( 1st iterable, 2nd iterable, etc)
___________
take iterables (can be zero or more), makes iterator that aggregates elements based on the iterables passed, and returns an iterator of tuples.

A

zip()