PieceOfAPie
PieceOfAPie
  • Home
  • Tutorials
  • More
    • Home
    • Tutorials
  • Home
  • Tutorials

String Methods

Previous Lesson


In Python, we have things called methods. Methods are basically functions. Some methods are built into Python like the print() method. You'll learn more about methods when you go into Object Oriented Programming. For now, string methods are some useful methods to use on strings. Here are some examples:

  • .strip() -- Removes any blank spaces from a string
  • .split() -- Splits the string into subsections and returns an array of all the subsections
  • .lower() -- Makes all the characters lowercase
  • .upper() -- Makes all the characters uppercase
  • len() -- Returns the count of all the characters in a string including spaces
  • isupper() -- Returns True if all the characters of a string are uppercase
  • islower() -- Returns True if all the characters of a string are lowercase
  • isnumeric() -- Returns True if all the characters of a string are numbers
  • .find(String) -- Returns the index number of the char was found (works for list)
  • .count(String) -- Returns how many times a certain character has occurred in a string (works for list)


Here is an example of each of them used in a program:

  • Examples of String Methods

You use string methods so that there is no variation of an answer you are expecting. For example, if you ask "what's my name", the user can say "Anish", "anish", "ANISH", "   AnIsH", or more. When you try to filter out the answers, it will be really hard because the user can input a variety of different texts. Instead, if we use a couple of string methods, we can expect one answer: "anish". Remember, string methods create a new copy of the original string and doesn't change the string itself. To store the copy, you have to put the string method in a variable.


In Python, you can also nest methods. Nesting means chaining string methods one after the other in a single expression so that the next string method processes the output of the previous one. Here is an example below:

  • Nesting String Methods


String Methods Exercise

Make a program that asks for a user input and using string methods, print a message if the user gets it right and print another message for a wrong answer.

Next Lesson

File Handling

Copyright © 2024 PieceOfAPie - All Rights Reserved.

Powered by GoDaddy

This website uses cookies.

We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.

Accept