String Methods - mrprov12/DSPrep GitHub Wiki

String Methods

Strings are sequences

Recall from earlier that strings are a sequence type in Python, but they are also immutable. This means they can be iterated through and sliced, for example, but do not support indexed reassignment or the del statement.

declaring a string

string = '' string = "" casting -- > str(element_to_be_cast)

repetition

string*num repeats string num number of times

containment

"p" in "python" returns True

[instance of dataype].method

str.upper()

str.lower()

str.title()

str.endswith()

returns a boolean

str.replace(x, y)

ie. "Homer" ->> replace('o', 'O') returns "HOmer"

help(str)

returns directory of str commands (exit w/ q)

str.capitalize()

string slicing:

[2:4] = [incl, ecl] ie. in carrot, would return 'rr' [4] would return 4th char

concatenation:

'xyz' + '123' returns 'xyz123'

fstring: print(f"... {} ...")

.split([separator [, maxsplit]])

braks up str at specified separator returns list of stirngs seperator (optional): if not specified, any whitespace maxsplit (optional): defines max number of splits; default is -1 meaning no limit

.count(substring, start=..., end=...)

searches substring and returns # of instances

.format

"single_and_escaped = 'I won't use anything other than single quotes!"

.isspace()

checks if character is a whitespace char liek ' ', '\t', '\n', '\r' etc

.index(substring[, start[, end]])

substring: to be search in str start/end: (optional) within str [st:end] returns lowed index in str where found

.isalnum()

returns True is all char alphaneumeric

.isalpha()

returns True if all char in alphabets

.is digit()

.isnumeric()

.join(iterable)

"".join(lst)

returns str by joining all elelments of an iterable, separated by a str separator (concatenates) data types: list, tuple, string, dict, set file obj + obj defined with iter() or getitem() method

.replace(old, new[, count])

returns copy of str where all occuranes of a subsring are replaced by another substring old: substring to replace new: new substring to replace old count: (optional) number of times to replace old with new (if not specified, will replace all)