How to Get The Length of a String in Python?

Code example to extract the length of a string in Python.

How to Get The Length of a String in Python?
Photo by Markus Winkler / Unsplash

To get the length of a script in Python, you can use the len() method. This internal function is available to you without installing any extra packages.

Here's an example of how to do it:

my_string = "this is my string"
length_of_my_string = len(my_string)

The method len() will return an int value that you can either store in a variable or use in more complex expressions like if statements like so:

if len(my_string) > 20:
  print("the string is too long")

The len() method can be used on strings, lists, and any iterable objects. You can read more about the len method in the official documentation.

Have any questions? Let me know in the comments below!

Want to join a community of software engineers helping each other? Join the Let's Code discord right here.