Get the String Length and Size in Python

  1. Get the String Length in Python
  2. Get the String Size in Python

Strings are a prevalent data type and are used in almost every programming language. It is a collection of characters and can be considered as an array of characters.

In Python, anything enclosed between quotation marks, single or double, can be considered as a string.

This tutorial will introduce how to get the length and size of a string in Python.

Get the String Length in Python

We can create our little function to get the length of a string in Python. The function will iterate through every character in the string using a for loop and increment a counter variable on every iteration until the string’s end is encountered. The following code implements this:

x = 'Sample String'
length = 0

for i in x:




We can also use the len() function to find the length of a string. For example:

x = 'Sample String'



Note that the len() function may provide unwanted results at times; for example, it does not count \ character in escape sequences, as shown below.




Get the String Size in Python

The size of the object is the number of bytes in the memory allocated for this object. The sys module has a function called getsizeof() that returns an object’s memory size in bytes. See the following example code.

import sys

x = 'Sample String'



DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Strip Punctuation From a String in Python
  • Reverse a String in Python