Teachnique
      CourseRoadmaps
      Login

      OverviewCommentsUser InputNumbersBooleansHistoryHello World ProgramEnvironment SetupSyntaxVariablesData TypesType CastingUnicode SystemLiteralsOperators

      Control FlowBreak StatementContinue StatementPass StatementNested LoopsDecision MakingIf StatementIf-else StatementNested IF StatementMatch-Case StatementLoopsFor LoopsFor-else LoopsWhile Loops

      FunctionsBuilt-in FunctionsDefault ArgumentsKeyword ArgumentsKeyword-Only ArgumentsPositional ArgumentsPositional-Only ArgumentsArbitrary ArgumentsVariable ScopeFunction AnnotationsModules

      StringSlicing StringsModify StringsString ConcatenationString FormattingEscape CharactersString MethodsString Exercises

      ListsList ExercisesAccess List ItemsChange List ItemsAdd List ItemsRemove List ItemsLoop ListsList ComprehensionSort ListsCopy ListsJoin ListsList Methods

      TuplesAccess Tuple ItemsUpdate TuplesUnpack Tuple ItemsLoop TuplesJoin TuplesTuple MethodsTuple Exercises

      SetsAccess Set ItemsAdd Set ItemsRemove Set ItemsLoop SetsJoin SetsCopy SetsSet OperatorsSet MethodsSet Exercises

      DictionariesDictionary ExercisesAccess Dictionary ItemsChange Dictionary ItemsAdd Dictionary ItemsRemove Dictionary ItemsDictionary View ObjectsLoop DictionariesCopy DictionariesNested DictionariesDictionary Methods

      ArraysAccess Array ItemsAdd Array ItemsRemove Array ItemsLoop ArraysCopy ArraysReverse ArraysSort ArraysJoin ArraysArray MethodsArray Exercises

      File HandlingWrite to FileRead FilesRenaming and Deleting FilesDirectoriesFile Methods

      OOP ConceptsDynamic BindingDynamic TypingAbstractionObject and ClassesEncapsulationInterfacesPackagesInner ClassesAnonymous Class and ObjectsSingleton ClassWrapper ClassesEnumsReflectionClass AttributesClass MethodsStatic MethodsConstructorsAccess ModifiersInheritancePolymorphismMethod OverridingMethod Overloading

      Feedback

      Submit request if you have any questions.

      Course
      String Methods

      Python Tutorial

      This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.

      String Methods

      Python's built-in str class defines different methods. They help in manipulating strings. Since string is an immutable object, these methods return a copy of the original string, performing the respective processing on it.
      The string methods can be classified in following categories −
      • Case conversion
      • Alignment
      • Split and join
      • Boolean
      • Find and replace
      • Formatting
      • Translate

      Case conversion

      This category of built-in methods of Python's str class deal with the conversion of alphabet characters in the string object. Following methods fall in this category
      Sr.No.
      Method & Description
      1
      AI
      Capitalizes first letter of string
      2
      AI
      Converts all uppercase letters in string to lowercase. Similar to lower(), but works on UNICODE characters alos
      3
      AI
      Converts all uppercase letters in string to lowercase.
      4
      AI
      Inverts case for all letters in string.
      5
      AI
      Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.
      6
      AI
      Converts lowercase letters in string to uppercase.
      Let us discuss these methods with examples

      Alignment

      Following methods in the str class control the alignment of characters within the string object.
      Sr.No.
      Methods & Description
      1
      AI
      Returns a string padded with fillchar with the original string centered to a total of width columns.
      2
      AI
      Returns a space-padded string with the original string left-justified to a total of width columns.
      3
      AI
      Returns a space-padded string with the original string right-justified to a total of width columns.
      4
      AI
      Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
      5
      AI
      Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).
      Here is the detailed explanation of each of the above methods

      Split and join

      Python has the following methods to perform split and join operations
      Sr.No.
      Method & Description
      1
      AI
      Removes all leading whitespace in string.
      2
      AI
      Removes all trailing whitespace of string.
      3
      AI
      Performs both lstrip() and rstrip() on string
      4
      AI
      Splits the string from the end and returns a list of substrings
      5
      AI
      Splits string according to delimiter (space if not provided) and returns list of substrings.
      6
      AI
      Splits string at NEWLINEs and returns a list of each line with NEWLINEs removed.
      7
      AI
      Splits the string in three string tuple at the first occurrence of separator
      8
      AI
      Splits the string in three string tuple at the ladt occurrence of separator
      9
      AI
      Concatenates the string representations of elements in sequence into a string, with separator string.
      10
      AI
      Returns a string after removing the prefix string
      11
      AI
      Returns a string after removing the suffix string
      Print Page

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.
      

      Boolean

      Following methods in str class return True or False.
      Sr.No.
      Methods & Description
      1
      AI
      Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
      2
      AI
      Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
      3
      AI
      Returns true if the string contains only digits and false otherwise.
      4
      AI
      Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
      5
      AI
      Returns true if a unicode string contains only numeric characters and false otherwise.
      6
      AI
      Returns true if string contains only whitespace characters and false otherwise.
      7
      AI
      Returns true if string is properly "titlecased" and false otherwise.
      8
      AI
      Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
      9
      AI
      Returns True is all the characters in the string are from the ASCII character set
      10
      AI
      Checks if all the characters are decimal characters
      11
      AI
      Checks whether the string is a valid Python identifier
      12
      AI
      Checks whether all the characters in the string are printable
      Let us discuss these methods with examples 
      

      Find and replace

      Following are the Find and Replace methods in Python
      Sr.No.
      Method & Description
      1
      AI
      Counts how many times sub occurs in string or in a substring of string if starting index beg and ending index end are given.
      2
      AI
      Determine if sub occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
      3
      AI
      Same as find(), but raises an exception if str not found.
      4
      AI
      Replaces all occurrences of old in string with new or at most max occurrences if max given.
      5
      AI
      Same as find(), but search backwards in string.
      6
      AI
      Same as index(), but search backwards in string.
      7
      AI
      Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring sub; returns true if so and false otherwise.
      8
      AI
      Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.

      Translation

      maketrans()

      The maketrans() method returns a mapping table. It maps each character from astr to a character at same index in bstr. The mapping table returned by this method may be used by translate() method to replace the characters.

      Syntax

      var.maketrans(astr, bstr, cstr)

      Parameters

      • astr − This can be either dictionary or string. If only one parameter is supplied, this parameter must be a dictionary. If two or more parameters are given, this parameter has to be a string specifying the characters to be replaced.
      • bstr − This is the string having corresponding mapping character.
      • cstr − Optional. The string parameter specifies the characters to remove in the string.

      Return Value

      This method returns a translate table to be used translate() function.

      Example

      
      var = 'Explicit is better than implicit.'
      table = var.maketrans({'i':'I'})
      print ("original string:", var)
      print ("translation table:", table)
      
      var1 = var.translate(table)
      print ("Translated string", var1)
      
      var = "Explicit is better than implicit."
      table = var.maketrans("than", "then")
      print ("original string:", var)
      print ("translation table:", table)
      var2 = var.translate(table)
      print ("Translated string", var2)
      
      var = 'Explicit is better than implicit.'
      table = var.maketrans("is","as", "s")
      print ("original string:", var)
      print ("translation table:", table)
      var3=var.translate(table)
      print ("Translated string", var3)
      When you run this program, it will produce the following output
      original string: Explicit is better than implicit.
      translation table: {105: 'I'}
      Translated string ExplIcIt Is better than ImplIcIt.
      original string: Explicit is better than implicit.
      translation table: {116: 116, 104: 104, 97: 101, 110: 110}
      Translated string Explicit is better then implicit.
      original string: Explicit is better than implicit.
      translation table: {105: 97, 115: None}
      Translated string Explacat a better than amplacat.

      translate()

      The translate() method returns a string where each character is replaced by its corresponding character in the translation table created by the maketrans() method.

      Syntax

      var.translate(table)

      Parameters

      • table − A translation table created by the maketrans() method.

      Return Value

      This method returns a translated copy of the string.

      Example

      var = 'Explicit is better than implicit.'
      table = var.maketrans({'i':'I'})
      print ("original string:", var)
      print ("translation table:", table)
      
      var1 = var.translate(table)
      print ("Translated string", var1)
      
      var = "Explicit is better than implicit."
      table = var.maketrans("than", "then")
      print ("original string:", var)
      print ("translation table:", table)
      var2 = var.translate(table)
      print ("Translated string", var2)
      
      var = 'Explicit is better than implicit.'
      table = var.maketrans("is","as", "s")
      print ("original string:", var)
      print ("translation table:", table)
      var3=var.translate(table)
      print ("Translated string", var3)
      When you run this program, it will produce the following output
      original string: Explicit is better than implicit.
      translation table: {105: 'I'}
      Translated string ExplIcIt Is better than ImplIcIt.
      original string: Explicit is better than implicit.
      translation table: {116: 116, 104: 104, 97: 101, 110: 110}
      Translated string Explicit is better then implicit.
      original string: Explicit is better than implicit.
      translation table: {105: 97, 115: None}
      Translated string Explacat a better than amplacat.

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.