Learning common Python string methods is easier than it sounds as Python is very flexible with its data types. Most programming languages require you to declare what kind of variable you are using beforehand, whether an integer or string or another type. Python doesn’t. Python is a dynamically typed, interpreted language.

Within Python, variables are strictly typed (they have a single type) and dynamically typed (you don’t need to declare the variable’s type when you declare it). As with many other languages, a “string” in Python is just a sequence of characters. 

Because of that, you sometimes need to validate strings in Python or format them. In this tutorial, we’ll look at the most common Python string methods.

Glasses in front of screen with code

What is a “string” in Python?

A string is any variable that falls between single quotes (‘Hello!’) or double quotes (“Hello!”). Declaring a string is simple:

sstring = “1” = “Hello, world!”

Because Python doesn’t provide for static typing, you don’t need to do anything else. For instance, in other languages, you’d need to declare:

str $stringGreeting = “Hello, world!”;

But in Python, you can have a variable like this:

string = “1”

This is a string. But it’s also a number. In other words, in most Python operations, you’ll be able to use that as an integer rather than as a string. It’s both.

Keep this in mind as you look at some of the most popular Python string methods or dig into Python programming projects.

The Complete Python Bootcamp From Zero to Hero in Python

Last Updated July 2023

  • 156 lectures
  • All Levels
4.6 (517,033)

Learn Python like a Professional Start from the basics and go all the way to creating your own applications and games | By Jose Portilla, Pierian Training

Explore Course

What are Python string methods?

Python string methods are functions designed to validate and format Python strings. They are separate from functions or commands. So, with a given STRING, you would be looking at whether STRING are printable, STRING are lowercase, STRING are numeric, etc.

Sometimes a Python string method returns true if the string matches a specific case. Otherwise, it returns false. Other Python string methods are just used to format text — it returns a string that’s been properly formatted. 

From machine learning to GUIs, string methods are important to ensure that data gets formatted and printed correctly.

Why are Python string methods used? 

Let’s say that you take user information on someone’s name. They enter the name in:

john doe

And that’s fine. But that’s certainly not what you want to put on their forms and on the GUI. You want to make it:

john doe

At its most basic, this is what many string methods do. String methods can also tell you if something is improperly capitalized, if it’s got whitespace (blank characters) in it, or if it has non-alphanumeric characters in it.

Data validation isn’t just for things like GUIs or forms. Data validation is essential because otherwise, you could accidentally inject dangerous information into a database like SQLite, or you could inject information into a machine learning program that it can’t actually use.

Whenever you need a certain type of validated input in Python, you should use string methods. You should also use string methods to put data into a program such as a database.

What is a method vs. a function?

At this point, you might be wondering: What’s the difference between a method and a function? A method is essentially a function that’s linked directly to an object. In Python, text functions link directly to the text itself. So, while in another language, you might do this:

$string = “Hello!”;
upper($string);

In Python, you do this:

string = “Hello!”
string.upper()

As you can see, the method is directly attached to the string, rather than being a disassociated block of code. Methods are essentially functions and are often referenced interchangeably, but the difference is that you need to call a method through the given object.

Now, let’s take a deeper look at the most common string methods.

1. text.capitalize(): capitalize a letter

This Python function capitalizes the first letter of a string. Note that if this string is an entire sentence, it will not capitalize every word; just the first word. But if you wanted to capitalize a name, for instance, you could use text.capitalize.

Example:

text = “hello”
text.capitalize()

Result:

Hello

2. text.center(): center the text

This Python method will center the string with the given number of empty spaces. This is usually used for text-based user interfaces.

Example:

text = “hello”
text.center(12)

Result:

      hello      

3. text.count(): Count occurrences of a given string

This Python method will count the occurrences of a given needle within the given haystack. In other words, how many times a letter or a string of letters occurs inside of a larger phrase. So you might use this to count how many commas or spaces were in a string.

Example:

text = “hello”
text.count(“l”)

Result:

2

4. text.endswith(): Determine whether the text ends with a string

This Python method will return “true” if the string ends with the given string and “false” if it does not. So, you might want to know, for instance, if a string ends with a semicolon (maybe you’re too used to programming in a language that isn’t Python).

Example:

text = “Hello, world!”
print(text.endswith(“!”))

Result:

True

5. text.index(): Returns the position of a string within a string

This Python function returns the position of a string within a string, giving the character basis of the first occurrence of that string.

Example:

text = “Hello, world!”
print(text.index(“world”))

Result:

7

6. text.isalnum(): Determines whether all characters are alphanumeric

This Python function returns true if all characters in a string are alphanumeric and false if they are not. You can use this for things like user input validation or to validate data before it’s entered into a database.

Example:

text = “Hello, world!”
print(text.isalnum())

Result:

False

7. text.isalpha(): Returns true if all characters are letters

This Python function returns true if all characters in a string are letters and false if they aren’t. Like text.islanum(), this can be used for things like user input validation.

Example:

text = “Hello, world!”
print(text.alpha())

Result:

False

8. text.isdigit(): Returns true if all characters are numbers

This Python function returns true if all characters in a string are numbers and false if they aren’t. Like text.islanum(), you can use this for things like user input validation. These functions can be particularly useful because Python doesn’t follow strict-typing.

Example:

text = “Hello, world!”
print(text.isdigit())

Result:

False

9. text.islower(): Returns true if all characters are lowercase

This Python function checks a string and says “True” if everything is lowercase. Now, note that you could also use text.lower() and just ensure that all characters are lowercase.

Example:

text = “Hello, world!”
print(text.islower())

Result:

False

10. text.isprintable(): Returns true if all characters can be printed

This Python function is great if you need to validate data before it’s printed. It returns true if characters can be printed and false if they cannot.

Example:

text = “Hello, world!”
print(text.isprintable())

Result:

True

11. text.istitle(): Returns true if string is in title case

This Python string method returns true if the string is already in the title case. Note that like text.islower(), you could also just use text.title() to make sure that the string is in the title case rather than validating it, but there are times when you can’t just rewrite the text.

Example:

text = “Hello, world!”
print(text.istitle())

Result:

False

12. text.isupper(): Returns true if string is in upper case

Like text.title(), this Python string method is concerned with capitalization. It checks to see whether the entire string is in uppercase. You could use this for things like natural language processing (is someone “SHOUTING”)?

Example:

text = “Hello, world!”
print(text.isupper())

Result:

False

13. text.ljust(): Left justify a given string

Left justification means that a string is padded but aligned to the side specified. This operates like the text.center() command.

Example:

text = “Hello, world!”
print(text.ljust(12))

Result:

Hello, world!               

(In the above result, there are 12 pieces of white space to the right.)

14. text.lower(): Converts all text to lowercase

This Python string method converts all the text in a string to lowercase. Similarly, you can use text.upper() to convert all text to uppercase.

Example:

text = “Hello, world!”
print(text.lower())

Result:

hello, world!

15. text.lstrip(): Returns a string with leading characters deleted

Any leading characters in a string are deleted using this Python string function. Leading characters are whitespace or tab characters that don’t actually add anything printable.

Example:

text = ”        Hello, world!”
print(text.lstrip())

Result:

Hello, world

16. text.replace(): Replace all occurrences of a string with another string

With the text.replace() function, Python searches a string for a substring and replaces it. You can use it to replace individual characters or whole strings.

Example:

text = “Hello, world!”
print(text.replace(“world”,”everyone”))

Result:

Hello, everyone!

19. text.rjust(): Right justifies a text string

This Python string method works just like text.ljust() but with right justification. These are frequently used in text-based GUIs.

Example:

text=”Hello, world!”
print(text.rjust(12))

Result:

            Hello, world!

20. text.rstrip(): Remove trailing characters from the end of a string

Like text.lstrip(), text.rstrip() removes whitespace characters, this time from the end of the string. This is commonly used in text formatting so data can be used otherwise, such as entering into a database.

Example:

text = “Hello, world!              “
print(text.rstrip())

Result:

Hello, world!

21. text.startswith(): Returns true if the string starts with a value

The Python function text.startswith() returns true if a string starts with a given substring. This can be important when finding or sorting data.

Example:

text = “Hello, world!”
print(text.startswith(“Hello”)

Result:

True

22. text.strip(): Strips whitespace from beginning and ending of string

This Python function is a text.lstrip and text.rstrip combined and is designed for fast data formatting. 

Example:

text = ”                Hello, world!                          “
print(text.strip())

Result:

Hello, world!

23. text.swapcase(): Swaps the cases of lowercase and uppercase characters

This is sort of a unique Python function because there’s no direct rationalization for why it exists—it just swaps cases. So, something like “Abcde” swaps to “aBCDE.” It’s a pretty specialized function that isn’t frequently used.

Example:

text = “Hello, world!”
print(text.swapcase())

Result:

hELLO, WORLD!

24. text.title(): Converts a string to title case

This can be a very useful function for validation as it automatically converts a string directly to title case.

Example:

text = “Hello, world!”
print(text.title())

Result:

Hello, World!

25. text.upper(): Converts entire text to uppercase

Want to shout? This Python method converts all the text in a string directly to uppercase, the opposite of text.lower().

Example:

text = “Hello, world!”
print(text.upper())

Result:

HELLO, WORLD!

How do you remember all these Python methods?

In short: You don’t.

Most programmers have a secret. They don’t really know all the functions in a given language. If they need to, say, take a copy of the string, or perform concatenation of the strings, they look it up in the given manual.

For Python, that would be the Python documentation manual.  

There are more functions than most programmers will ever be able to remember. These aren’t even all of the Python string methods that exist—they’re just the built-in methods that are most commonly used. You can always extend Python by adding other libraries, too. And in addition to string methods, there are also number methods, list methods, and so forth.

A lot of programming is more about knowing what is possible. Logically, you think through the process:

Learning about and practicing programming is more about knowing what’s possible than raw memorization. The more you remember, of course, the easier and faster you will find programming—but that’s something that only comes with time.

Taking the next steps

Python is one of the fastest programming languages to learn. It’s also one of the most desirable. Python is used in everything from machine learning to natural language processing to creating an excellent web application.If you want to learn more about Python, the fastest way is to get started with some Python programming projects. Most people learn by doing. If you have a project that you want to get started with (such as a great mobile app), you can download a Python IDE and jump in.

Page Last Updated: March 2022

Top courses in Python

Python for Beginners
Navin Reddy
4.6 (9,465)
Python for Beginners (2023)
AlgoSTEM Inc.
4.5 (3,112)
Python 3: Deep Dive (Part 1 - Functional)
Dr. Fred Baptiste
4.8 (11,682)
Python for Data Analysis & Visualization
Malvik Vaghadia, Pathfinder Analytics
4.6 (1,632)
100 Days of Code: The Complete Python Pro Bootcamp
Dr. Angela Yu, Developer and Lead Instructor
4.7 (322,255)
Bestseller
Learn Python & Ethical Hacking From Scratch
Zaid Sabih, z Security
4.7 (19,797)
Artificial Intelligence: Reinforcement Learning in Python
Lazy Programmer Team, Lazy Programmer Inc.
4.8 (10,224)
Bestseller
Learn Python Programming Masterclass
Tim Buchalka, Jean-Paul Roberts, Tim Buchalka's Learn Programming Academy
4.6 (102,988)
REST APIs with Flask and Python in 2024
Jose Salvatierra, Teclado by Jose Salvatierra
4.6 (23,070)
Bestseller

More Python Courses

Python students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo