String Methods in Python with examples

Spread the love

Python supports many built-in methods to manipulate strings. A method is just like function. The only difference between a function and method is that a method is invoked or called on an object. For example, if the variable str is a string, then you can call the upper() method as str.upper() to convert all the characters of str in uppercase.

The following table discusses some of the most commonly used string methods.

MethodUsageExample
capitalize()This method is used to capitalize first letter of the string.str = ‘hello’
print(str.capitalize)
output –
Hello
center(width, fillchar)Returns a string with the original string centered to a total of width columns and filled with fillchar in columns that do not have characters.str = ‘hello’
print(str.center(10, ‘*’))
output –
**hello***
count(str, beg, end)Counts number of times str occurs in a string. You can specify beg as 0 and end as the length of the message to search the entire string or use any other value to just search a part of the string.str = ‘he’
message = ‘helloworldhellohello’
print(message.count(str, 0, len(message)))
output –
3
endswith(suffix, beg, end)Checks if string ends with suffix. returns True if so and False otehrwise. You can either set beg=0 and end equal to the length of the message to search entire string or use any other value to search a part of it.message = ‘She is my best friend’
print(message.endswith(‘end’, 0, len(message)))
output –
True
startswith(prefix, beg, end)Checks if string starts with prefix. If so, it returns True and False otherwise.str=’The world is beautiful’
print(str.startswith(‘Th’, 0, len(str)))
output –
True
find(str, beg, end)Checks if str is present in string. If found it returns the position at which str occurs in string, otherwise returns -1. message= ‘She is my best friend’
print(message.find(‘my’, 0, len(message)))
output –
7
index(str, beg, end)Same as find but raises an exception if str is not found.message = ‘she is my best friend’
print(message.index(‘mine’, 0, len(message)))
output –
ValueError: substring not found
rfind(str, beg, end)Same as find but starts searching from the endstr = ‘Is this your bag?’
print(str.rfind(‘is’, 0, len(str)))
output –
5
rindex(str, beg, end)Same as index but start searching from the end and raises an exception if str is not foundstr = ‘Is this your bag?’
print(str.rindex(‘you’, 0, len(str)))
output –
8
isalnum()Returns True if string has at least 1 character and every character is either a number or an alphabet and False otherwise.message = ‘JamesBond007’
print(message.isalnum())
output –
True
isalpha()Returns True if string has at least 1 character and every character is an alphabet and False otherwise.message=’JamesBond007′
print(message.isalpha())
output –
False
isdigit()Returns True if string contains only digits and False otherwise.message=’007′
print(message.isdigit())
output –
True
islower()Returns True if string has at least 1 character and every character is a lowercase alphabet and False otherwise.message = ‘Hello’
print(message.islower())
output –
False
isspace()Returns True if string contains only whitespace characters and False otherwise.message = ” “
print(message.isspace())
output –
True
isupper()Returns True if string has at least 1 character and every character is an uppercase alphabet and False otherwise.message = ‘HELLO’
print(message.isupper())
output –
True
len(string)Returns the length of the string.str = ‘Hello’
print(len(string))
output –
5
ljust(width[, fillchar])Returns a string left-justified to a total of width columns. Columns without characters are padded with the character specified in the fillchar argument.str = ‘Hello’
print(str.ljust(10, ‘*’))
output –
Hello*****
rjust(width[, fillchar])Returns a string right justified to a total of width columns. Columns without characters are padded with the character specified in the fillchar argument.str = ‘Hello’
print(str.rjust(10, ‘*’))
output –
*****Hello
zfill(width)Returns string left padded with zeros to a total of width characters. It is used with numbers and also retain its sign (+ or -)str = ‘1234’
print(str.zfill(10))
output –
0000001234
lower()Converts all characters in the string into lowercase.str = ‘Hello’
print(str.lower())
output –
hello
upper()Converts all characters in the string into uppercase.str = ‘Hello’
print(str.upper())
output –
HELLO
lstrip()Removes all leading whitespace in string.str = ‘ Hello ‘
print(str.lstrip())
output –
‘Hello ‘
rstrip()Removes all trailing whitespace in stringstr = ‘ Hello ‘
print(str.rstrip())
output –
‘ Hello’
strip()Removes all leading and trailing whitespaces in string.str = ‘ Hello ‘
print(str.strip())
output –
‘Hello’
max(str)Returns the highest alphabetical character (having highest ASCII value) from the string.str = ‘hello friendz’
print(max(str))
output –
z
min(str)Returns the lowest alphabetical character(lowest ASCII value) from the string.str = ‘hello friendz’
print(min(str))
output –
D
replace(old, new [, max])Replaces all or max( if given) occurrences of old in string with new.str = ‘hello hello hello’
print(str.replace(‘he’, ‘FO’))
output –
FOlloFOlloFOllo
title()Returns string in title case.str = ‘The world is beautiful’
print(str.title())
output –
The World Is Beautiful
swapcase()Toggles the case of every character( uppercase characters becomes lowercase and vice versa)str = ‘The World Is Beautiful’
print(str.swapcase())
output –
tHE wORLD iS bEAUTIFUL
split(delim)Returns a list of substrings separated by the specified delimiter. If no delimiter is specified then by default it splits strings on all whitespace characters.str = “abc,def, ghi,jkl”
print(str.split(‘,’))
output –
[‘abc’, ‘def’, ‘ ghi’, ‘jkl’]
join(list)It is just opposite of split. The function joins a list of strings using the delimiter with which the function is invoked.print(‘-‘.join([‘abc’, ‘def’, ‘ghi’, ‘jkl’]))
output –
abc-def-ghi-jkl
isidentifier()Returns True if the string is a valid identifier.str = ‘Hello’
print(str.isidentifier())
output –
True
enumerate(str)Returns an enumerate object that lists the index and value of all the characters in the string as pairs.str= ‘Hello World’
print(list(enumerate(str)))
output –
[(0, ‘H’), (1, ‘e’), (2, ‘l’), (3, ‘l’), (4, ‘o’), (5, ‘ ‘), (6, ‘W’), (7, ‘o’), (8, ‘r’), (9, ‘l’), (10, ‘d’)]

Related Posts –

  1. Python String Method – Capitalize()
  2. Python String Method – title()
  3. Python String Method – center()
  4. Python String Method – count()
  5. Python String Method – startswith()
  6. Python String Method – endswith()
  7. Python String Method – find()
  8. Python String Method – index()
  9. Python String Method – isalnum()
  10. Python String Method – isalpha()
  11. Python String Method – isdecimal()
  12. Python String Method – isdigit()
  13. Python String Method – islower()
  14. Python String Method – istitle()
  15. Python String Method – isupper()
  16. Python String Method – join()
  17. Python String Method – lower()
  18. Python String Method – upper()
  19. Python String Method – swapcase()
  20. Python String Method – lstrip()
  21. Python String Method – rstrip()
  22. Python String Method – strip()
  23. Python String Method – replace()
  24. Python String Method – zfill()

Rating: 1 out of 5.

Leave a Reply