Back to series
· 1 min read

Definition and Operations of Python Strings (str)


I. Basic Concepts of Strings

1.1 What Is a String

A string (String) is text data composed of a series of characters, used to represent text, symbols, numeric text, and other Unicode characters.

Python uses the built-in type str to represent strings.

name = "Python"
message = "Hello, World!"
number_text = "12345"

print(type(name))  # <class 'str'>
print(type(message))  # <class 'str'>

Strings are a sequence type and have the following characteristics:

  • Ordered: characters are arranged in a certain order.
  • Indexable: elements at a specified position can be accessed by index.
  • Slicable: a substring within a specified range can be extracted.
  • Iterable: a string can be traversed using for.
  • Immutable: the characters in it cannot be modified directly after creation.
  • Supports sequence operations: supports operations such as length calculation, membership testing, concatenation, and repetition.
text = "Python"

print(len(text))       # 6
print(text[0])         # P
print(text[-1])        # n
print("Py" in text)    # True
print(list(text))      # ['P', 'y', 't', 'h', 'o', 'n']

1.2 Strings Are Unicode Text Sequences

In Python 3, str is used to represent Unicode text.

Unicode assigns code points to the characters in the vast majority of the world's writing systems, for example:

Character Unicode Code Point
A U+0041
中 U+4E2D
€ U+20AC