Python String objects has many built in methods.
The following are the details of each string method with examples:
Return the lowest index in the string where substring sub is found
>>> s = "this is an example"
>>> s.find('an')
8
>>> s = "this is an example"
>>> s.find('is') # 'is' is available in 'this', so it gives the first occurrence
2
>>> s = "this is an example"
>>> s.find('sample') # 'sample' is not available, so it returns -1
-1
str.rfind(sub[, start[, end]]) - Return the highest index in the string where substring sub is found
>>> s = "This is Python and it is easy"
>>> s.find('is'), s.rfind('is')
(2, 22)
find() gives lowest index and rfind() gives highest index of "is" respectively
Return a copy of the string with all occurrences of substring old replaced by new
>>> s = "python is very easy"
>>> s.replace('easy', 'hard')
'python is very hard'
If there is no substring avaialble it returns the origional string
>>> s = "python is very easy"
>>> s.replace('java', 'programming')
'python is very easy'
Return a string which is the concatenation of the strings in iterable
>>> ",".join(["python", "is", "easy"])
'python,is,easy'
>>> "-".join(["python", "is", "easy"])
'python-is-easy'
>>> "+".join(["python", "is", "easy"])
'python+is+easy'
>>> " ".join(["python", "is", "easy"])
'python is easy'
>>> "+".join(("python", "is", "easy"))
'python+is+easy'
>>> "+".join({"python": 15, 'is': 'easy'})
'python+is'
A TypeError
will be raised if there are any non-string values in iterable
>>> ",".join(["my age", "is", 10])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 2: expected str instance, int found
>>>
In the above example 10 is an integer, so it raise TypeError
The separator between elements is the string providing this method.
>>> 1.join(["python", "is", "easy"])
File "<stdin>", line 1
1.join(["python", "is", "easy"])
^
SyntaxError: invalid syntax
Return the number of non-overlapping occurrences of substring
>>> s = "this is an example"
>>> s.count('is')
2
>>> s.count('sample')
0
In the above example "is" sub string presents 2 times in the string. So it prints 2 .
But "sample" is not present so it prints 0
Like find()
, but raise ValueError
when the substring is not found.
>>> s = "this is an example"
>>> s.index('is')
2
>>> s.index('sample')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>
str.find() never raises error, but str.index() raises.
str.rindex(sub) is same as str.index(sub), but it gives higest index rather than lowest
str.split(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string
>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']
If sep is not specified or is None
>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> ' 1 2 3 '.split()
['1', '2', '3']
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
If sep is not specified or is None
>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
str.format(*args, **kwargs)
Perform a string formatting operation.
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
str.encode(encoding="utf-8", errors="strict")
Return an encoded version of the string as a bytes object
>>> s = 'this is an example'
>>> s.encode()
b'this is an example'
>>>
Return a copy of the string with all the cased characters
>>> s = 'this is an example'
>>> s.upper()
'THIS IS AN EXAMPLE'
Return a copy of the string with all the cased characters
>>> s = 'THIS IS AN EXAMPLE'
>>> s.lower()
'this is an example'
Return a casefolded copy of the string
>>> s = 'THIS IS AN EXAMPLE'
>>> s.casefold()
'this is an example'
Casefolding is similar to lower() but more aggressive because it is intended to remove all case distinctions in a string
For example, the German lowercase letter 'ß'
is equivalent to "ss"
. Since it is already lowercase, lower()
would do nothing to 'ß'
; casefold()
converts it to "ss"
>>> 'ß'.lower()
'ß'
>>> 'ß'.casefold()
'ss'
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.
>>> 'hello world'.title()
'Hello World'
Return a copy of the string with its first character capitalized and the rest lowercased.
>>> 'hello world'.capitalize()
'Hello world'
Remember title() makes each word's first letter of a string to Upper case, but capitalize() makes the first letter of wole string
>>> s = "they're bill's friends from the UK"
>>> s.capitalize()
"They're bill's friends from the uk"
In the above example you can see only the first letter is capital, others are small. Even it makes 'UK' to 'uk'
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
>>> s = "This is Python and it is easy"
>>> s.partition("is")
('Th', 'is', ' is Python and it is easy')
>>> s.partition("sample")
('This is Python and it is easy', '', '')
str.lstrip([chars]) - Return a copy of the string with leading characters removed
>>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
str.rstrip([chars]) - Return a copy of the string with trailing characters removed.
>>> ' spacious '.rstrip()
' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
str.startswith(prefix[, start[, end]])
Return True
if string starts with the prefix, otherwise return False
>>> s = "they're bill's friends from the UK"
>>> s.startswith('they')
True
prefix can also be a tuple of prefixes to look for
>>> prefix_strings = 'they', 'he'
>>> s = "they're bill's friends from the UK"
>>> p = "he is bill's friends from the UK"
>>> s.startswith(prefix_strings), p.startswith(prefix_strings)
(True, True)
str.endswith(suffix[, start[, end]])
Return True if the string ends with the specified suffix, otherwise return False
>>> s = "they're bill's friends from the UK"
>>> s.endswith('UK')
True
>>> s.endswith('uk')
False
suffix can also be a tuple of suffixes to look for
>>> suffix_strings = 'UK', 'US'
>>> p = 'he is from US'
>>> e = 'he is from UK'
>>> p.endswith(suffix_strings)
True
>>> e.endswith(suffix_strings)
True
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise
>>> "asd".isalpha()
True
>>> "".isalpha()
False
>>> "asd123".isalpha()
False
Return true if the string is empty or all characters in the string are ASCII
>>> "asd".isascii(), "".isascii(), "asd123".isascii(), "ß".isascii()
(True, True, True, False)
Return true if all characters in the string are decimal characters and there is at least one character, false otherwise
>>> "123".isdecimal(), "asd".isdecimal(), "".isdecimal(), "asd123".isdecimal()
(True, False, False, False)
Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise.
>>> "½¼".isnumeric(), "123".isnumeric(), "a1".isnumeric()
(True, True, False)
Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise
>>> "12".islower()
False
>>> "12a".islower()
True
>>> "12aA".islower()
False
>>> "".islower()
False
>>> "adsasdasd".islower()
True
>>> "adsasdasd1".islower()
True
Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
>>> "AB".islower()
True
>>> "12A".isupper(), "12aA".isupper()
(True, False)
Return true if the string is a titlecased string and there is at least one character
>>> "This is Title".istitle()
False
>>> "This Title".istitle()
True
>>> "This'Title".istitle()
True
>>>
Return true if there are only whitespace characters in the string and there is at least one character, false otherwise
>>> "This Title".isspace()
False
>>> "This ".isspace()
False
>>> " ".isspace()
True
>>> "1 ".isspace()
False
Comment here