Ways to Get Length of String in Python
We will discuss different methods to get the length of string in Python.
Strings are mutable in Python and have a certain number of characters that correspond to their length.
The most direct method is by using the len() function.
To get length of string in Python:
- Use the
len()
function.
See the code below.
# Get Length of String in Python string = 'educatepython' length = len(string) print(length) # Output: 13
An alternative approach to this can be to use the for
loop. With the for
loop, we can traverse through the string and set a counter variable which is incremented in every iteration.
To get length of string in Python:
- Use the
for
loop to iterate through the string. - Increment a counter variable in every iteration.
See the code below.
# Get Length of String in Python string = 'educatepython' length = 0 for i in string: length += 1 print(length) # Output: 13
We can also get the size of the string in Python. The size corresponds to the bytes it occupies in the memory.
For this, we can use the sys.getsizeof() function. This function computes the size of an object.
To get size of string in Python.
- Use the
sys.getsizeof()
function.
See the code below.
# Get Size of String in Python import sys string = 'educatepython' size = sys.getsizeof(string) print(size) # Output: 62
To conclude
This particular tutorial demonstrated several methods to get length of string in Python. The first method uses the len()
function and the second method demonstrates the for
loop.
Additionally, we also discuss how to get the size of string in Python using the sys.getsizeof()
function.
Explore more from this category at Python Strings. Alternatively, search and view other topics at All Tutorials.