PythonPython StringsPython string fundamentals

What is a string in Python?

Question 60 of 88 · Updated

On this page

A string in Python is an immutable sequence of Unicode code points represented by the built-in str type. Strings store and manipulate text such as names, messages, identifiers, document contents and user input. Python 3 treats text and binary data as separate types: str represents text, while bytes represents an immutable sequence of byte values.

The built-in data-types lesson introduced str alongside Python's other types. This lesson develops the text model that the rest of the strings module relies on, particularly the distinction between code points, displayed characters, encoded bytes and object references.

1. Creating and identifying a string#

PYTHON
text='Python' print(type(text).__name__,len(text),bool('')) print(type(text[0]).__name__)

Output:

str 6 False
str

The variable text refers to a string containing six Unicode code points. Python does not have a separate built-in character type: accessing one position in a string returns another str of length one.

A string can be empty. The literal '' represents an empty string, whose length is zero and whose truth value is false. An empty string is not None, and it is distinct from a string containing spaces.

Single-quoted, double-quoted and triple-quoted string literals are all ways to construct text in source code. The next lesson explores the quotation forms, escaping and multiline literals in detail. A string can also be obtained from a function, decoded from bytes, or constructed using the str type.

2. The fundamental properties of str#

PropertyMeaning
TextualRepresents Unicode code points, not arbitrary encoded bytes
OrderedEach code point occupies a position in the sequence
ImmutableExisting string values cannot be modified in place
IterableA for loop can consume successive one-code-point strings
Indexable and sliceableIndividual positions and subsequences can be selected
HashableOrdinary strings can be keys in dictionaries or elements of sets
Case-sensitive by defaultOrdinary equality distinguishes different letter cases

These properties define the logical text value. They do not require an implementation to store every code point in an independent object or to use a particular internal encoding.

CPython's flexible string representation, described in PEP 393, can use different internal storage widths according to the contents of a string. Applications should rely on the str interface, not assumptions about the interpreter's internal memory layout.

3. Unicode code points versus visible characters#

Unicode assigns numerical code points to text elements. For example, the Latin capital letter A is U+0041, and the precomposed lowercase letter é is U+00E9.

Some text that looks like a single character can be represented by multiple code points. A base letter followed by a combining accent is one common example. Many emoji sequences also consist of several code points that may be displayed as one grapheme cluster.

PYTHON
a='café' b='cafe\u0301' import unicodedata as ud print(len(a),len(b),a==b) print(ud.normalize('NFC',b)==a)

Output:

4 5 False
True

The string a ends with the precomposed é. The string b ends with the ordinary letter e followed by U+0301, COMBINING ACUTE ACCENT. They are canonically equivalent Unicode text, but their raw sequences of code points differ. Ordinary Python equality compares those sequences, so the two strings are unequal until the demonstrated normalization is applied.

Loading diagram…

The built-in len function counts Unicode code points, not the number of grapheme clusters or the display width on a terminal. A program that truncates a user's name by code-point count can unintentionally split a combined character. User-facing length limits, cursor movement and visual layout may need a Unicode-aware segmentation or display-width policy.

Normalization is not universally desirable. Some protocols, identifiers or digital signatures require exact original sequences. Decide the normalization contract at the application boundary rather than normalizing every string indiscriminately. NFC handles canonical equivalence; it does not generally make all visually similar characters equal or provide locale-aware comparison.

4. Text and bytes are different data types#

A str object contains text. A bytes object contains integer byte values from 0 to 255. To transfer text through a binary interface, encode it using a specified character encoding. To interpret encoded bytes as text, decode them using the appropriate encoding.

PYTHON
text='Aé🙂' raw=text.encode('utf-8') print(len(text),len(raw)) print(raw.hex(),raw.decode('utf-8')==text)

Output:

3 7
41c3a9f09f9982 True

The original string contains three code points. In UTF-8, A occupies one byte, é occupies two and the smiling emoji occupies four. The encoded byte sequence therefore has seven bytes.

Loading diagram…

Encoding is not the same as encryption or compression. It defines a representation of text using bytes. UTF-8 is one encoding; not every byte sequence represents valid UTF-8 text.

Decoding invalid UTF-8 with ordinary strict error handling raises UnicodeDecodeError. Other error policies can replace or discard invalid data, which may be inappropriate for exact records, identifiers or security-sensitive values. Choose the policy explicitly.

5. Strings cannot be changed in place#

PYTHON
text='cat' other=text text=text.upper() print(text,other) print({'cat':3}[other])

Output:

CAT cat
3

The name other retains the original lowercase text. Calling upper obtains an uppercase string result and the assignment rebinds text to that result. The original string remains unchanged.

Attempting to assign to an individual string position raises TypeError. Strings do not provide list-style in-place editing operations.

The earlier mutability lesson explained object references and rebinding. Here the important implication is that string transformations must be used through their returned results. Calling a method that returns a changed representation without using that result does not change the original string.

String immutability also supports stable hashing within a process, which makes strings suitable as ordinary dictionary keys and set elements. Python's string hash is not a portable persistent identifier: its value can differ between interpreter processes. For persistence or content integrity, choose an explicitly specified stable representation and hash algorithm as appropriate.

Do not rely on object identity for text equality. An interpreter may reuse immutable objects, including some strings, but that is not the ordinary test for equivalent string values.

6. Constructing text from other objects#

PYTHON
print(str(42),str(None)) print(str(b'abc'),b'abc'.decode('utf-8'))

Output:

42 None
b'abc' abc

The str constructor produces a string representation of an object. The value 42 becomes the text '42', and None becomes the text 'None'. Neither resulting string has the original object's type.

Calling str on bytes without specifying an encoding normally produces a representation of the bytes object, including the b prefix and quotation marks. To obtain the text represented by those bytes, decode them with the expected encoding.

Conversion is not validation. For example, converting an unexpected None value into the string 'None' might accidentally accept missing input. Decide whether the input is already required to be a string or whether other types may be converted.

For user-defined objects, the string representation can be customized using the object's string-conversion protocol. The built-in str function is not a general serialization format and should not be assumed to produce reversible or machine-readable representations of arbitrary objects.

7. Displayed text versus a debugging representation#

PYTHON
text='A\nB' print(text) print(repr(text),len(text))

Output:

A
B
'A\nB' 3

The actual string contains three code points: A, a newline and B. Printing it normally renders the newline as a line break. The repr function produces a representation useful for debugging, with the newline shown as an escape sequence.

The representation is itself a string; the quotation marks and escape notation are part of that representation, not the original text's contents.

This distinction is useful when troubleshooting invisible whitespace, unexpected newlines and delimiters. Use repr or other appropriately escaped diagnostic formatting to inspect text, while respecting privacy and avoiding logging secrets. Do not assume repr of every arbitrary object can be safely evaluated to reconstruct that object.

8. Common operations on strings#

TaskPython interface
Count code pointslen(text)
Test substring presencesubstring in text
Select a position or intervalIndexing or slicing
Obtain a different letter caseupper(), lower(), casefold()
Remove selected boundary charactersstrip(), lstrip(), rstrip()
Split or combine textsplit(), join()
Substitute matching textreplace()
Locate a substringfind(), index()
Format values into textf-strings, format() or other formatting interfaces
Encode for a binary interfaceencode()

These are an overview of the module, not interchangeable operations. Each has its own input requirements, output behavior and edge cases.

For example, the membership operator tests whether a substring occurs anywhere in another string, whereas equality compares the complete value. Text methods may return strings, lists, integers or Booleans depending on their purpose. A string object itself remains immutable.

The following lessons address these operations separately, including indexing, slicing, concatenation, formatting, splitting, joining and substring search.

9. Practical example: read and write a UTF-8 text file#

PYTHON
from tempfile import TemporaryDirectory from pathlib import Path with TemporaryDirectory() as folder: path=Path(folder)/'note.txt' path.write_text('café',encoding='utf-8') print(path.read_text(encoding='utf-8')) print(path.read_bytes().hex())

Output:

café
636166c3a9

The example creates a file inside an isolated temporary directory. The write_text method encodes the supplied string as UTF-8. The read_text method decodes the file contents back to str. The read_bytes method returns the stored byte representation directly.

The file contains five bytes, although its decoded string contains four code points. The temporary directory is removed when the context manager exits.

Specify an encoding when the file format defines one. Do not guess that a file uses UTF-8 merely because it contains text. If a legacy system uses another documented encoding, decode using that encoding and a deliberate error policy.

For large files, reading the whole file as one string can require considerable memory. Iterating through a text stream or reading bounded chunks can be preferable. Text stream decoding, newline handling and chunk boundaries have their own considerations, covered later in the file-handling curriculum.

10. Practical example: validate a text-only field#

PYTHON
def label(value): if not isinstance(value,str): raise TypeError('expected text') if not value.strip(): raise ValueError('empty label') return value.strip() print(label(' Asha ')) try: label(' ') except ValueError as exc: print(exc)

Output:

Asha
empty label

The function requires a string input, removes boundary whitespace and rejects a result containing no remaining text. It returns a cleaned string without modifying its original argument.

This is a deliberately small label policy. It does not establish that a label is unique, culturally appropriate, free of control characters, safe to embed in HTML or suitable for an identifier. Define additional requirements at the actual input boundary. Use parameterized database operations, context-appropriate escaping and other trusted interfaces instead of treating generic string cleanup as a security control.

In an implementation that needs only one trimmed result, assign the result of strip to a local name and reuse it. The explicit two calls here demonstrate validation and the returned text; they need not be repeated in production code.

11. Complexity and memory considerations#

String operation costs depend on the operation, text lengths, implementation and sometimes the contents.

For ordinary CPython strings:

OperationTypical cost model
len(s)Constant-time length retrieval
Access one valid indexConstant-time position access under the implementation's representation
Copy a proper slice of k code pointsO(k) time and resulting storage
Encode n code points to UTF-8O(n) traversal and output storage proportional to encoded byte count
Concatenate two strings of lengths n and mGenerally proportional to the resulting length when copying is needed

These are conventional implementation-level estimates, not universal language guarantees or exact timing predictions. Object reuse, special cases, internal string representation, codec behavior and allocation costs can affect them.

Repeatedly constructing an ever-growing string may copy previous text many times. When combining many fragments, consider collecting them and using join, or using a text stream such as io.StringIO. Detailed concatenation and joining trade-offs are reserved for their dedicated lessons.

Always consider the output size. Even a logically simple operation can allocate substantial memory if the resulting string is very large.

12. Common errors#

The following four failure cases were independently confirmed.

OperationExpected exception
Assign a new value to a position of an existing strTypeError
Add a str directly to a bytes objectTypeError
Decode the byte 0xFF as strict UTF-8UnicodeDecodeError
Access index 3 in a three-code-point stringIndexError

Other common mistakes include confusing an empty string with None, assuming len measures visible characters, overlooking case-sensitive equality, assuming normalization is automatic and expecting a string method to modify its original argument.

When working with user text, choose whether exact sequence preservation, canonical normalization, case-insensitive comparison or language-specific collation is required. Those are different operations with different contracts.

Frequently asked questions#

What is the type of a Python string?#

The built-in type is str. Ordinary text literals in Python 3 create str objects.

Does Python have a separate char data type?#

No. A single code point selected from a string is represented by another string of length one.

Are strings mutable?#

No. String values cannot be changed in place. Operations can obtain other string results, and names can be rebound to those results.

Is len(text) the size of the string in bytes?#

No. It counts code points. The byte length depends on the encoding used to represent that text. It also differs from an object's full in-memory storage cost.

Can a string contain non-English text or emoji?#

Yes. Python 3 strings represent Unicode code points and can contain text from many writing systems and emoji sequences. Some displayed characters consist of multiple code points.

Are two visually identical strings always equal?#

No. They can contain different code-point sequences. Canonically equivalent sequences can be made comparable with an appropriate normalization policy, but visual similarity alone does not guarantee equality.

Interview-ready answer#

A string in Python is an immutable, ordered sequence of Unicode code points represented by str. Strings support indexing, slicing, iteration, searching and many text transformations. Python has no separate char type; an indexed code point is itself a one-code-point string. String operations do not change the original value in place. Text differs from bytes: encoding converts text to a byte representation, and decoding converts bytes back to text according to a specified encoding. The length of a string counts code points, not encoded bytes or necessarily displayed characters. Correct text processing accounts for Unicode representation, normalization, immutability and explicit I/O encoding.

Official references#

Verification note: All eight fenced Python example groups were executed in independent namespaces on CPython 3.13.5 and matched their documented outputs. Four independent expected-exception tests passed. The two triple-backtick fenced Mermaid diagrams were manually reviewed. The local Mermaid package and CLI were unavailable, so parser validation and public-site rendering were not performed. Grapheme segmentation and terminal display width were discussed conceptually rather than tested using a third-party segmentation library. Official links are provided under the authorized offline research exception; live documentation and the Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design