What is the maximum length of a string in Python?


The maximum length of a string that is supported in Python depends on the amount of memory available on your system and the implementation limit of Python version that is being used. In the default implementation of Python, which is CPython, strings are stored as arrays of characters in memory and are limited to a maximum length of 2⁶³ - 1 bytes which is nearly 9 million terabytes. However, this limit can be different depending on what characters the string contains due to the way CPython implements strings.

This means that as long as there is enough memory, and if length of string is within the implementation limit of Python version you are using. you can create a string of any length you want.

Here's an example of creating a string in Python −

Example

my_string = "Hello, world!"

In this example, my_string is a variable that holds a string of text.

You can change the text to be anything you want by assigning a new value to the variable −

Example

my_string = "Goodbye, world!"

Now my_string holds a different string of text.

If you want to concatenate two strings (join them together), you can use the + operator −

Example

string1 = "Hello, "
string2 = "world!"

my_string = string1 + string2
print(my_string)

Output

Hello, world!

Now my_string holds the value "Hello, world!".

In summary, there is no maximum length for a string in Python as long as there is enough memory available on the computer, and if length of string is within the implementation limit of Python version you are using.

Updated on: 08-May-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements