A quick overview of Python string methods.
String methods:
- str.capitalize(): Returns copy of the string with its first character capitalized and rest of the letters in lowercase.
https://gist.github.com/IndhumathyChelliah/81895342b5ba10f27a4dc20ac0c5e9c3
- str.title()– Returns a copy of string where the first character in every word is upper case.
https://gist.github.com/IndhumathyChelliah/958f75b0dc2e3e57ca21dc1d56ee9c50
- str.casefold(): Returns case folded copy of the string. Converts string to lower case. Case folding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string.
https://gist.github.com/IndhumathyChelliah/0cd19a488cb46bdf8c1eac4f499e4226
- str.swapcase(): Returns a copy of the string with uppercase characters converted to lowercase and vice versa.
https://gist.github.com/IndhumathyChelliah/63345bbabad1254825cf11d07471bb76
- str.lower()-Returns copy of the string in lowercase. Symbols and numbers are ignored.
https://gist.github.com/IndhumathyChelliah/ec38ba41a4d3db4accd807613ead578d
- str.upper()-Returns copy of the string in uppercase. Symbols and numbers are ignored.
https://gist.github.com/IndhumathyChelliah/b6e26395c8caf99cab1b125d57ef5cfb
- str.encode():Returns an encoded version of the string in byte format.
str.encode(encoding=”encoding”,errors=”errors”)
encoding(Optional):Default encoding is “utf-8”
errors(Optional):Default errors is “strict”.Raise unicode error.
https://gist.github.com/IndhumathyChelliah/62a1e32e483f3bdf41e22d05dcd86263
- str.startswith()-Returns
True
, if the string starts with specified value, otherwise returnsFalse.
str.startswith(suffix,start,end)
start,end-(optional)-starting and ending index
https://gist.github.com/IndhumathyChelliah/6f60e3ae249f88253969f236e038f69c
- str.endswith()-Returns
True
,if the string ends with specified value,otherwise ReturnsFalse
str.endswith(suffix,start,end)
start,end — (optional)-starting and ending index.
https://gist.github.com/IndhumathyChelliah/9d88ec30edee96c0f8df500d871d9239
- str.isalnum()– Returns
True
if all characters in the string are alphanumeric(alphabets [A-Za-z] and numbers[0–9] are alphanumeric) and there is at least one character. Otherwise returnsFalse.
https://gist.github.com/IndhumathyChelliah/668bdf7f42341a946d66d9002fe6096f
- isalpha()– Returns
True
if all characters in the string are alphabetic(A-Za-z) and there is at least one character. Otherwise returnsFalse
.
https://gist.github.com/IndhumathyChelliah/3263680a68d2d37b76192cdd9e498367
- isascii() — Returns
True
if the string is empty or all characters in the string are ASCII. Otherwise returnsFalse
.
Supported in python version 3.7 and above.
https://gist.github.com/IndhumathyChelliah/c6fcb086f2033bb98ad93863fb75d9db
isdecimal() — Returns True
if all characters in the string are decimal and there is at least one character. Otherwise Returns False
.
The decimal number are numbers that can be used to form numbers in the base of 10.
isdigit()– Returns True
if all characters in the string are digits and there is at least one character. Otherwise Returns False.
Superscripts, subscripts, and decimal characters are included in digits.
isnumeric()-Returns True
if all characters in the string are numeric characters and there is at least one character. Otherwise Returns False.
Superscripts, subscripts, decimal numbers, fractions, roman numerals in unicode are considered to be numeric.
https://gist.github.com/IndhumathyChelliah/da52b4e7baf791af166680d893838cab
- istitle()– Returns
True
if a string is a title case string and there is at least one character. Otherwise ReturnsFalse
. - isupper()– Returns
True
if all cased characters in the string are uppercase. Otherwise ReturnsFalse
.Numbers, symbols, and spaces are not checked. - islower()– Returns
True
if all cased characters in the string are lowercase.Other ReturnsFalse
.Numbers, symbols, and spaces are not checked.
https://gist.github.com/IndhumathyChelliah/a1e2f7deb71a7bffaaa16ae3ccfe10ca
- isspace(): Returns
True
if there is only whitespace in the string and there is at least one character. Otherwise ReturnsFalse
.
https://gist.github.com/IndhumathyChelliah/1b3d523f61410ff82b727adad58da214
- isidentifier():Returns
True
if the string is the valid identifier.It can contain lowercase letters(a-z),upper case letters(A-Z),digits(0–9) and underscore _.It should not begin with digits or contain any spaces. Special characters are not allowed.
https://gist.github.com/IndhumathyChelliah/dfdca9ab6364b4e4c373d42e08e5bccc
- isprintable():Returns
True
if all characters in the string are printable or empty. Otherwise ReturnsFalse
.
https://gist.github.com/IndhumathyChelliah/30e764a0699790db3708caa841737e15
- str.split(): Returns list of all words in the string using
sep
as the delimiter string.
If maxsplit is given, at most maxsplits are done and the list will have at mostmaxsplits+1
elements.
If maxsplit is not specified or -1, there is no limit for the number of splits.
Ifsep
is given, it is used for splitting the string. By default, white space is a separator.sep
argument may consist of multiple characters also.
str.split(sep=None,maxsplit=-1)
- str.rsplit(): Returns a list of words in the string, using sep as the delimiter string.
If maxsplit is given, almost maxsplits are done, the rightmost ones.
If sep is not specified or None, whitespace string is a separator.
Except for splitting from the right,rsplit() behaves like split().
str.split(sep=None,maxsplit=-1)
https://gist.github.com/IndhumathyChelliah/73c999a9a465a457d9c9e8163c87c1f4
- str.splitlines(): Returns list of all lines in the string, breaking at line boundaries.
If keepends is True, linebreaks are included in the string, Otherwise not included. The default value is False.
str.splitlines(keepends)
https://gist.github.com/IndhumathyChelliah/ce6dffa8a0ca87bc85d575b7a2a355ba
- str.find(): Returns the lowest index in the string where the substring
sub
is found within the slices[start: end]
.Return-1
if the sub is not found.
start, end-Optional arguments.
str.find(sub,start,end)
- str.rfind(): Returns the highest index in the string where the substring
sub
is found within the slices[start:end]
.Return-1
if the sub is not found.
start ,end-Optional arguments.
str.rfind(sub,start,end)
- str.index(): Similar to find(), Returns the lowest index of the substring found in the string. Raises
ValueError
, when the substring is not found. - str.rindex(): Similar to find(), Returns the highest index of the substring found in the string. Raises
ValueError
, when the substring is not found.
https://gist.github.com/IndhumathyChelliah/e0987c9feca9579cd0987fe20724fafb
- str.strip(): Returns copy of the string with leading(spaces at the beginning) and trialing (spaces at the end)characters removed.
chars
– The char’s argument is a string specifying the set of characters to be removed.
chars
argument is not a prefix, rather all combinations of its value are stripped.
Ifchars
is not specified, whitespace is removed.
str.strip(chars)
- str.lsrtip():Same as strip(),but only leading characters are removed.
- str.rstrip():Same as strip(),but only trailing characters are removed.
https://gist.github.com/IndhumathyChelliah/e114eb65e5a246d3e386d291e1694c65
- str.center(): Returns a copy of string which is aligned in the center of length(width) padded with fillchar(default fillchar is an ASCII space). If the width mentioned is less than the length of the string means, the original string is returned.
str.center(width,fillchar)
fillchar(optional)-padding character
- str.rjust(): Return a string right-justified in a string of length(width).Padding is done by using the fillchar. The default fillchar is an ASCII space. The original string is returned if the width is less than or equal to len(s)
str.rjust(width,fillchar)
- str.ljust():Similar to rjust(),but return a string left-justified.
https://gist.github.com/IndhumathyChelliah/5c37c493e08fece36ef3fe7593e8d610
- str.partition(): Spilt the string at the first occurrence of sep and return 3-tuple containing the part before separator, the separator itself, and the part after separator.
If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
str.partition(sep)
- str.rpartition():Same as partition(), but split the string at last occurrence of sep.
str.rpartition(sep)
https://gist.github.com/IndhumathyChelliah/8f764f22b629f808afac70855a4d929b
- str.format():Performs string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument or the name of a keyword argument.
Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
str.format(*args,**kwargs)
https://gist.github.com/IndhumathyChelliah/19af13861cadc8c5d33c566515e794ad
- str.format_map(): Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict.
str.format_map(mapping)
mapping- input dictionary
https://gist.github.com/IndhumathyChelliah/be84773d6acab00e85a42a1eeeae599b
- str.join(): Return a string which is the concatenation of all strings in the iterable. Returns a TypeError, if there are non-string values in the iterable. The separator between elements is the string providing this method.
str.join(iterable)
https://gist.github.com/IndhumathyChelliah/da3c45d270e0c13d9eb748b8e68e3ea5
- str.replace(): 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.
str.replace(old,new,count)
https://gist.github.com/IndhumathyChelliah/2f37ad9cd54e576a0d106ff340d5a97f
- str.zfill(): Returns a copy of string by adding zeros(0) at the beginning of the string to make the string of length(width). If the width mentioned is less than or equal to the length of the string, then the original string is returned. A leading sign prefix (‘+’/’-’) is handled by inserting the padding after the sign character rather than before.
str.zfill(width)
https://gist.github.com/IndhumathyChelliah/42adb75456b149deea8f8a19c684280e
- str.expandtabs(): Return a copy of the string, where all tab characters are replaced by one or more spaces, depending on the current column and given tab size.
str.expandtabs(tabsize=8)
https://gist.github.com/IndhumathyChelliah/623e20df6fb36a7ccfc4ca1023837e40
- str.maketrans():Returns a mapping table for translation usable for translate() function.
str.maketrans(x,y,z)
x- The string specifying the list of characters that need to be replaced
y-The string specifying the list of characters which is used for replacing x
z-The string specifying the list of characters to be deleted.
If only one argument is mentioned, it should be dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths), or None
If two arguments are mentioned, it should be strings of equal length. Each character is x is mapped to the character at the same position in y.
If the third argument is mentioned, it is mapped to “None” in the result.
- str.translate(): Returns copy of the string in which each character has been mapped through the given translation table.
str.translate(table)
table- translate mapping used to make the translation
https://gist.github.com/IndhumathyChelliah/5be6504615b8e4e091f08d2547f76250
- count(): Returns the number of occurrences of a substring in the string.
str.count(sub,start,end)
start, end(optional) — starting index and ending index
sub-substring, whose count is to be found.
https://gist.github.com/IndhumathyChelliah/7c0e95a342930cf97330d481b0c361f2
Conclusion
- Return Type is Boolean str.startswith(),str.endswith(),isalnum(),isalpha(),isascii(),isdigit()
isdecimal(),isnumeric(),isupper(),islower(),istitle(),isspace(),
isidentifier(),isprintable() - Return Type is String
str.capitalize(),str.title(),str.casefold(),str.swapcase(),str.lower(),
str.upper(),str.center(),str.encode(),str.strip(),str.rstrip(),str.lstrip(),str.rjust(),str.ljust(),str.format(),str.format_map(),str.join(),str.zfill(),
str.expandtabs(),str.translate() - Return Type is an integer value.
str.count(),str.find(),str.rfind(),str.index(),str.rindex() - Return Type is List
str.split(),str.splitlines(),str.rsplit() - Return type is tuple
str.partition(),str.rpartition() - Return type is dictionary
str.maketrans() - Returns True if string is empty
isascii(),isprintable() - String methods which doesn’t take any parameters.
isalnum(),isalpha(),isascii(),isdigit(),isdecimal(),isnumeric(),islower(),
isupper(),istitle(),isspace(),isidentifier(),isprintable(),str.capitalize(),
str.title(),str.casefold(),str.swapcase(),
str.lower(),str.upper() - isascii() — Supported from Python version 3.7 and above
My other blogs on Python data structures
An Introduction to Python List
An Introduction to Python Tuple
An Introduction to Python Dictionary
Resources
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee