Best post on string methods in python – 3

String methods in python

Python supports various compound datatypes like String, tuple,dictionary etc.

In previous post we studied about how strings are immutable and what are string operations?

In this post we will be concentrating on various string methods.

String consist of various methods for easy functioning and utilization of python script.

Many methods like find(), capitalize(), upper() lower() len() etc are used to provide various functionalities and can be used again and again as per need without need of coding again this helps in reducing redundancy. 

 

List of string methods

  • capitalize()
    • It returns a capitalized version of string, i.e. make the first character have upper case and the rest lower case.
    • S.capitalize()
  • count()
    • It returns the number of occurrences of sub string in string S[start:end]. Optional arguments start and end are interpreted as in slice notation
    • S.count(sub[, start[, end]]) 
  • endswith()
    • Return True if String ends with the specified suffix, False otherwise.
    • S.endswith(suffix,start=0,end=len(string))
  • find()
    • It returns the lowest index in String where sub string is found,such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
    • It returns -1 if no match found.
    • S.find(str,start=0,end=len(string))
  • index()
    • It is like S.find() but raises ValueError when the sub string is not found.
    • S.index(str,start=0,end=len(string))
  • isalnum()
    • It returns True if all characters in String are alphanumeric and there is at least one character in String, False otherwise.
    • S.isalnum()
  • isalpha()
    • It returns True if all characters in String are alphabetic and there is at least one character in String, False otherwise.
    • S.isalpha()
  • isdigit()
    • It returns True if all characters in String are digits and there is at least one character in String, False otherwise.
    •  S.isdigit()
  • islower()
    • It returns True if all cased characters in String are lowercase and there is at least one cased character in String, False otherwise.
    • S.islower()
  • isspace()
    • It returns True if all characters in String are whitespace and there is at least one character in String, False otherwise.
    • S.isspace()
  • istitle()
    • It returns True if String is a titlecased string and there is at least one character in String , i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones and returns False otherwise.

  • isupper()
    • Return True if all cased characters in String are uppercase and there is at least one cased character in String , False otherwise
    • S.isupper()
  • len()
    • It returns the integer value of number of characters present in the string including whitespace character.
    • len(string)
  • lower()
    • It returns a copy of the string converted to lowercase.
    •  S.lower()
  • lstrip()
    • It returns a copy of the string with leading whitespace removed. 
    • If chars is given and not None, remove characters in chars instead.
    • S.lstrip([chars])
  • max()
    • It returns the character with maximum number of Unicode (integer ordinal)
    • max(str)
  • min()
    • It returns minimum (integer ordinal) value character.
    • min(str)
  • replace(old,new,max)
    • It returns a copy of String with all occurrences of sub string old replaced by new. If the optional argument count is
      given, only the first count occurrences are replaced.
    • replace(old,new,max)
  • rfind(str,start=0,end=len(string))
    • It returns the highest index in String where sub string is found, such that sub is contained within S[start:end]. Optional
      arguments start and end are interpreted as in slice notation.
    • It returns – on faliure.
    • S.rfind(str,start=0,end=len(string))
  • rindex(str,start=0,end=len(string))
    • It is like S.rfind() but raises ValueError when the sub string is not found.
    • S.rindex(str,start=0,end=len(string))
  • rstrip()
    • It returns a copy of the string with trailing whitespace removed.
    • If chars is given and not None, remove characters in chars instead.
    • S.rstrip([chars])
  • startswith(prefix,start=0,end=len(string))
    • It returns True if String starts with the specified prefix, False otherwise.
    • S.startswith(prefix,start=0,end=len(string))
  • swapcase()
    • It returns a copy of String with uppercase characters converted to lowercase and vice versa.
    • S.swapcase()
  • title()
    • It returns a titlecased version of String, i.e. words start with title case characters, all remaining cased characters have lower case.
    • S.title()

Example of string methods

#STRING METHODS IN PYTHON (itvoyagers.in)
s="itvoyagers welcome you"
print('s',s)
print("s.capitalize()",s.capitalize()) #returns capitalized string
print("s.count('e',0,22)",s.count('e',0,22))
print("s.endswith('s',0,22)",s.endswith('s',0,22))
print("s.endswith('u',0,22)",s.endswith('u',0,22))
print("s.find('O',0,22)",s.find('O',0,22)) #returns -1 if not found else index
print("s.find('e',0,22)",s.find('e',0,22)) #returns index if found
print("s.index('e',0,22)",s.index('e',0,22)) #returns index if found
#remove comment from below line to execute code
#print("s.index('E',0,22)",s.index('E',0,22)) #returns error if not found
st='5star'
print('st',st)
print("st.isalnum()",st.isalnum()) #returns True only if alphabets or numbers
st1='star'
print('st1',st1)
print("st1.isalpha()",st1.isalpha()) #returns True only if alphabets
st2='5'
print('st2',st2)
print("st2.isdigit()",st2.isdigit())
print("s.islower()",s.islower()) #returns True is string is in lower case
print("s.isupper()",s.isupper()) #returns True is string is in upper case
st3=' '
print('st3',st3)
print("st3.isspace()",st3.isspace()) #returns True if the string consist of only space characters
st4="Hello Python"
print('st4',st4)
print("st4.istitle()",st4.istitle()) #checks if string is in title case
print("len(s)",len(s))
print("s.lower()",s.lower())
print("s.upper()",s.upper())
st5="This is a pleasant day and it is warm weather"
print("st5",st5)
print("st5.replace('is','was',1)",st5.replace('is','was',1))
print("st5.replace(' is',' was',1)",st5.replace(' is',' was',1))
print("s.rfind('O',0,22)",s.rfind('O',0,22))
print("s.rfind('e',0,22)",s.rfind('e',0,22))
print("s.rindex('e',0,22)",s.rindex('e',0,22))
#remove comment from below line to execute code
#print("s.rindex('E',0,22)",s.rindex('E',0,22))
st6=" Python "
print("st6",st6)
print("st6.rstrip()",st6.rstrip()) #removes trailing whitespaces
print("st6.lstrip()",st6.lstrip()) #removes leading whitespaces
print("s.startswith('i',0,22)",s.startswith('i',0,22))
print("s.startswith('I',0,22)",s.startswith('I',0,22))
print("st5.title()",st5.title()) #returns title case
print("st5.swapcase()",st5.swapcase()) #swaps upper to lower and lower to upper case

Output of string methods in python

string methods in python (itvoyagers.in)

Other python related post

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon…….

Other advance python related post

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in ‘re’ module(Part I)- Match vs Search
Functions in ‘re’ module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
Best post on Select Query to Search & Read: Python + MySQL-4
Best post on Update query and Delete query : Python + MySQL-4
New posts coming soon…….
We are aiming to explain all concepts of Python in easiest terms as possible.
ITVoyagers-logo
ITVoyagers
Author

Leave a Comment