math
module.String
.
I am pretty sure that, in our Getting Started lesson, we looked at the basics of strings in Python.
if you didn't undergo through it, then head back and revise it, for this is the continuation from where we left.
>>> stringvar = 'I am string, quoted in single quotes'
>>> stringvar2= "I am another string, qouted in double quotes
>>> print(stringvar)
>>> print(stringvar2)
>>> introduction = "My name is Amin"
>>>print(introduction) # My name is Amin
>>> introduction = "My name is Amin."
>>> print(introduction[0]) # M
>>> print(introduction[1]) # y
>>> print(introduction) # My name is Amin
>>> introduction = "My name is Amin"
>>> print(introduction[0:7]) # My name
>>> print(introduction[3:7]) # name
>>> print(introduction[0:]) # My name is Amin
>>> introduction = "My name is Amin"
>>> print(introduction[0:11]+" John") My name is John
>>> print("Please tell your "+introduction[3:7]) Please tell me your name.
>>> print("I am tired!"[::-1]) # !derit ma I
>>> gate = "-"
>>> print(gate) # -
>>> print(gate*6) # ------
>>> print(gate*3) # ---
>>> intro= "My name is %s "
>>> print(intro % "Amin") My name is Amin
>>> print(intro % "Jane") My name is Jane
>>> print("%s is very good language." % "python") python is very good language.
len()
function : This function takes a string and returns the length of the string.>>> len("How many are this letters?") # 26
.capitalize()
capitalize()
Python string module is responsible for turning a string into first letter being the upper case letter.print("my name is Amin.".capitalize()) # My name is amin.
.center(width, fillchar)
center()
method of the string class adjust the string to the specified center.>>> text = 'center text'
>>> print(text.center(10,"0")) # "0000000000center text0000000000"
>>> print(text.center(5," ")) # " center text "
>>> print(text.center(6,'a') # "aaaaaacenter textaaaaaa"
.count(sub, start, end)
count()
conts the number of occurences of a given substring in the string.start
and end
are optional.>>> text = "There are two a's in this text"
>>> print(text.count('a')) # 2
>>> print(text.count('a',8)) # 1
>>> print(text.count('a',8,20)) # 1
.decode(encoding, errors)
decode()
function converts a string from one encoding to another. b"This is just binary encoded".decode(errors='replace') # This is just binary encoded.
.encode(encoding,errors)
.decode()
function and converts the string from one encoding to another.>>> print("Letter 'a' in UTF-16 is","a".encode("UTF-16","replace")) # Letter 'a' in UTF-16 is '\xff\xfea\x00'
.endswith(suffix, start, end)
.count()
, the .endswith()
string function traverse the string between start and end parameters,>>>print("Find the end".endswith('end')) # True
.expandtabs(tabsize)
.expandtabs()
function is a special case where tabs are expanded by spaces as provided in tabsize parameter.>>> text = "This is \t tab"
>>> print(text.expandtabs()) # This is tab
>>> print(text.expandtabs(4)) # This is tab
>>> print(text.expandtabs(12)) # This is tab
.find(sub, start, end)
.endswith()
, the .find()
function returns the lowest index where the first occurence of sub
parameter is found.-1
.>>> string = "This is test string"
>>> print(string.find("is")) # 2
>>> print(string.find("is",4,-1)) # 5
>>> print(string.find("lie")) # -1
.format()
>>> name = "My name is {name} Matola."
>>> print(name.format(name='Amin')) # My name is Amin Matola.
>>> print("There are {0} mangoes in the bag.".format(20)) # There are 20 mangoes in the bag.
.index(sub, start, end)
.index()
function works exactly as .find()
function and returns the lowest index where the first occurence of sub
parameter is found.>>> string = "This is test string"
>>> print(string.index("is")) # 2
>>> print(string.index("is",4,-1)) # 5
>>> print(string.index("lie")) # ValueError: substring not found
.isalnum()
True
, otherwise it returns False
>>> "am1".isalnum() # True
>>> "am1 ".isalnum() # False -- Space
>>> "".isalnum() # False -- Null
>>> " ".isalnum() # False -- Space
.isalpha()
.isalnum()
, except that this checks if all characters in a string are alphabetical characters (a to z, A to Z),
and there is atleast one character is the string. True
, otherwise returns False
.>>>print("am".isalpha()) # True
..isalnum()
above, and see the difference..isdigit()
True
, otherwise it returns False
>>> "am1".isdigit() # False
>>> "1".isdigit() # True
>>> "167562".isdigit() # True
>>> " ".isdigit() # False
.islower()
True
, otherwise it returns False
>>> "me".islower() # True
>>> "Me".islower() # False -- Uppercase 'M'
>>> "".islower() # False -- Null
>>> " ".islower() # False -- Space
.isspace()
space
test. It checks if a string containing atleast one character is/are space(s).True
, otherwise it returns False
>>> "am1".isspace() # False
>>> "am1 ".isspace() # False
>>> "".isspace() # False -- Null
>>> " ".isalnum() # True -- Space
.istitle()
True
, otherwise it returns False
>>>"am".istitle() # False
>>>"Am".istitle() # True
>>>"".istitle() # False -- Null
>>>" ".istitle() # False -- Space
.isupper()
True
, otherwise it returns False
>>> "me".isupper() # False
>>> "Me".isupper() # True -- Uppercase 'M' at beginning
>>> "".isupper() # False -- Null
>>> " ".isupper() # False -- Space
.join(iterable)
.join()
is a special case, and I am fond of using it.iterable
and returns string which is a concatenation of the items in the irable,>>> "".join([1,2,3,4,5]) # 12345
>>> "-".join([5,"April",2019]) # 5-April-2019
>>> "/".join(['C:','Users','Coder','Desktop']) # C:/Users/Coder/Desktop
>>> " ".isupper(["I","am","going"]) # I am going
.ljust(width, fillchar)
.center()
, but with .ljust()
, the string is aligned to the left,fillchar
parameter of this function.space
.
>>> "Tired".ljust(10,'-') #"Tired----------"
>>> "Tired".ljust(10) #"Tired "
.lower()
.lower()
function converts a string into all lower cases (a-z).
>>> "AMIN".lower() # amin
.lstrip([char])
char
arguments are not passed, then spaces are assumed.>>> " This is spaced".lstrip() # "This is spaced"
>>> "---Hyphens remove---".lstrip("-") # "Hypehns remove---" (only to the left)
.partition(sep)
.partition()
function takes a seperator, and returns a tupple of three elements,Head, Sep
and tail
.>>> Date = "05-April-2019"
>>> print(Date) # "05-April-2019"
>>> Date.partition("-") # ('05','-','April-2019')
>>> Date.partition(",") # ('05-April-2019','','')
.partition(sep)
.partition()
function takes a seperator, and returns a tupple of three elements,Head, Sep
and tail
.>>> Date = "05-April-2019"
>>> print(Date) # "05-April-2019"
>>> Date.partition("-") # ('05','-','April-2019')
>>> Date.partition(",") # ('05-April-2019','','')
.replace(old, new, count)
old
substrings of a string to the given new
substring.count
is given, then only the first count
occurences are replaced.>>> "people kill people".replace("people","animals") animals kill animals
>>> "people kill people".replace("people","animals",1) animals kill people
.rfind(sub, start, end)
.find()
, the .rfind()
function returns index of sub
in the string except
that the highest index which is the last occurence of sub
parameter is returned.-1
.>>> string = "This is test string"
>>> print(string.rfind("is")) # 5
>>> print(string.rfind("is",0,4)) # 2
>>> print(string.rfind("lie")) # -1
.rindex(sub, start, end)
.rindex()
function works exactly as .rfind()
function and returns the highest index where the last occurence of sub
parameter is found.>>> string = "This is test string"
>>> print(string.rindex("is")) # 5
>>> print(string.rindex("is",0,4)) # 2
>>> print(string.rindex("lie")) # ValueError: substring not found
.rjust(width, fillchar)
.ljust()
, but with .rjust()
, the string is aligned to the right,fillchar
parameter of this function.space
.
>>> "Tired".rjust(10,'-') #"----------Tired"
>>> "Tired".rjust(10) #" Tired"
.rpartition(sep)
.rpartition()
function takes a seperator, and returns a tupple of three elements,Head, Sep
and tail
.>>> Date = "05-April-2019"
>>> print(Date) # "05-April-2019"
>>> Date.rpartition("-") # ('05-April','-','2019')
>>> Date.rpartition(",") # ('05-April-2019','','')
.rsplit(sep,maxsplit)
.rsplit()
function returns a list of substrings (words), by deviding given string into smaller chuncks
using a given seperator (sep).maxsplit
is given, the split only occurs for maxsplit
times to the right.
>>> sentence = "I am going home"
>>> print(sentence.rsplit()) # ["I","am","going","home"]
>>> print(sentence.rsplit(" ",2)) ["I am","going","home"]
.rstrip([char])
char(s)
to the right of the string. If char
is not given,
then removes spaces
to the right of the string." Remove right space ".rstrip() # " Remove right space"
.split(sep,maxsplit)
.rsplit()
, this function returns the list of words by deviding a string into smaller chunks using a given sep
.
maxsplit
is given, the split only happens for maxsplit
times, else, the whole string will split.sep
is not given, the sep
will then default to whitespace
.>>> sentence = "I am going home"
>>> print(sentence.split()) # ["I","am","going","home"]
>>> print(sentence.split(" ",2)) ["I",am","going home"]
.splitlines(keepends=False)
split()
, this function returns the list of lines by deviding a string into lines using a
newline
('\n') as a separator.'\n'
however is not included in the resulting list except if keepends
keyword argument is turned True
.
>>> story = "I am going to school.\nAfter that, I'll go home."
>>> print(story.splitlines()) # ["I am going to school.","After that, I'll go home."]
>>> print(story.splitlines(True)) ["I am going to school.\n","After that, I'll go home."]
.startswith(prefix, start, end)
.endswith()
function;
this function checks whether a string is starting with the given substring prefix
string[start:end]
.
It turns True
if a given string is really starting with the prefix
, else, returns False
.tuple
>>> print("I am going".startswith("i")) # False -- lowercase
>>> print("I am going".startswith("am",2,6)) # True
>>> print("I am going".startswith(("Me","You","I")) # True
.strip([char])
.rstrip()
, this function is generic, and removes all white spaces to the Beginning and End of the string.char
is given, then the char(s) are removed to the begining and end of the string.>>> string = " spaces in here! "
>>> print(string.strip()) # 'spaces in here'
>>> print("---center---".strip('-')) # 'center'
.swapcase()
>>> "i NOW KNOW python".swapcase() # 'I now know PYTHON'
.title()
>>> "I am gone".title() # 'I Am Gone'
.translate(table)
.maketrans()
function of string,
which takes the first set of characters as the text which needs to be replaced, the second set of characters of which
to replace with, and the characters to delete.>>> question = "How are you?"
>>> table = question.maketrans("ear","swa")
>>> print(question.translate(table)) # "How was you?"
.upper()
.upper()
function does the opposite of .lower()
, >>> "amin".upper() # AMIN
.zfill(width)
width
, then no padding takes place because the string itsel is never truncated.>>> "125".zfill(5) # "00125"
string
module.string
module before you tag along with lists.