String Building Blocks
A Python string is an immutable sequence of Unicode characters. This section covers the fundamental concepts you need to create, access, and understand strings.
1. Declaring Strings
Python is flexible, offering several ways to declare a string. The method you choose often depends on the content of the string itself.
Single Quotes '...'
Simple and common. Use them when your string doesn’t contain any apostrophes.
Pyground
Create a simple greeting string using single quotes.
Expected Output:
Hello, Python!
Output:
2. Escape Sequences
Inside a regular string (non-raw), the backslash \
is used to “escape” characters, giving them a special meaning.
Sequence | Meaning |
---|---|
\n | Newline |
\t | Horizontal Tab |
\\ | Literal backslash |
\' | Single quote |
\" | Double quote |
Pyground
Print a string that shows a path on one line and a quoted message on the next.
Expected Output:
Path: C:\Data\Reports Message: She said "Keep learning!"
Output:
3. String Properties: Immutability and Length
Immutability
This is the most important property of Python strings. Once a string is created, it cannot be changed. Any function or method that seems to modify a string actually returns a new string.
Pyground
Attempt to change the first character of a string and observe the error.
Expected Output:
Error: 'str' object does not support item assignment Original word: Python New word: Jython
Output:
4. Accessing Characters: Indexing and Slicing
Since strings are sequences, you can access their parts using indexing and slicing.
Indexing
Access a single character using its zero-based index in square brackets []
. Negative indices count from the end of the string.
Pyground
From the word 'PYTHON', get the first character using a positive index and the last character using a negative index.
Expected Output:
First character: P Last character: N