A string is a sequence composed of independent characters, typically enclosed in single quotes (”), double quotes (“”), or triple quotes (”’ ”’ or “”” “””).
For example, the following representations are actually the same:
s1 = ‘python’s2 = “python” s3 = “””python””” print(s1==s2==s3)
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py05.py
True
Process finished with exit code 0
Python supports all three forms of representation, which is important because it allows you to embed strings with quotes within strings. For example:
s1 = “I’m a programmer”
Triple-quoted strings are mainly used for multi-line strings, such as function documentation, etc.
Some escape characters are summarized as follows:
Escape Character |
Description |
\ |
Backslash |
\’ |
Single Quote |
\” |
Double Quote |
\n |
New Line |
\t |
Horizontal Tab |
Example:
s1 = “re\ng\tina”print(s1)
re
g ina
String indexing, slicing, iteration, and length operations
name = ‘regina’print(len(name)) # Get string length
6print(name[0]) # Indexing
rprint(name[1:3]) # Slicing
eg
String indexing also starts from 0, where index=0 represents the first element (character), and [index:index+2] represents the substring composed of the element at index and the element at index+1.
for i in name:print(i)
r
e
g
i
n
a
Strings in Python, like in Java, are immutable, so the following operation will raise an error:
name = ‘regina’name[0] = ‘R’
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py05.py
Traceback (most recent call last):
File “D:/pyproject/py05.py”, line 2, in
name[0] = ‘R’
TypeError: ‘str’ object does not support item assignment
Process finished with exit code 1
If you want to modify it, you can do so using the following method:
name = ‘regina’name = ‘R’+name[1:] print(name) name = name.replace(‘R’,’r’) print(name)
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py05.py
Regina
regina
Process finished with exit code 0
Additionally, using the operator ‘+=‘ will also not violate the immutability of strings.
s = “”for i in range(0,100): s+=str(i) print(s)