g
Strings
Extract first character in string
Python follows zero-indexing. Indices start from \(0\).
Find length of string
Extract last character in string
Python allows negative indexing. An index of \(-1\) corresponds to the last character in a string, the index \(-2\) corresponds to the penultimate character, and so on.
Extract first five letters from string
Extract last three letters from string
End-index defaults to len(string)
when it is left unspecified,
Exclude first and last letter from string
Determine if a string is a substring of another
String together multiple strings
roll_number
in the code-below is an f-string or a formatted string. The values of the variables enclosed within {}
will get substituted.
Replicate string \(n\) times
Reverse string
The third argument after colon is the step-size. Here, the step size is \(-1\).
Convert string to lower case
Note that strings are immutable. This means that the string 'GREAT'
cannot be changed. When 'GREAT'.lower()
is called, the string 'great'
is returned. This new string is reassigned to word
. To understand this better, consider the following snippet:
Convert string to upper case
Count frequency of character in string
Replace character in string
Capitalize string
Check if string is in upper case
Check if string is in lower case
Check if string has only letters
Check if string has only numbers
Check if string has only letters and numbers
Find index of character that is present in string
index
will return the index if the character is present. It will throw an error if the character is not present. For an error-free way of handling this, check the next how-to.
Find index of character that may not be present in string
find
will return the index if the character is present. It will return \(-1\) if the character is not present.
Remove whitespaces from beginning and end of string
‘\n'
, '\t'
and ' '
are whitespaces. '\n
’ is the newline character, '\t'
is the tab character.