This document explains Python strings, including indexing, slicing concatenation, replication, immutability, escape sequences, and string methods for manipulating character data.
This document covers Python strings, including indexing, slicing, concatenation, replication, immutability, escape sequences, and string methods for manipulating character data.
Strings in Python are sequences of characters enclosed in quotes. They can contain letters, digits, spaces, and special characters.
Strings are ordered sequences, and each character can be accessed by its index.
Example:
1text = "Michael Jackson"
2first_char = text[0] # 'M'
3sixth_char = text[6] # 'l'
4thirteenth_char = text[13] # 'o'
5last_char = text[-1] # 'n'
Slicing and strides allow selection of multiple characters:
1# Select every second character
2text[::2]
3# Select every second character up to index 4
4text[:4:2]
len() to get the length of a string.+.*.Example:
1# Concatenation
2new_text = "Michael " + "Jackson"
3# Replication
4repeat_text = "Hi! " * 3 # 'Hi! Hi! Hi! '
Strings are immutable; their values cannot be changed, but new strings can be created by combining or modifying existing ones.
Escape sequences allow special formatting:
\n for new line\t for tab\\ for backslashr for raw stringsExample:
1print("Line1\nLine2") # Output on two lines
2print("Tab\tSpace") # Output with tab
3print("C:\\Users\\Name") # Output with backslashes
4print(r"C:\Users\Name") # Raw string
Strings have methods for manipulation:
upper(): Converts to uppercasereplace(): Replaces a substringfind(): Finds a substring indexExample:
1A = "Michael Jackson"
2B = A.upper() # 'MICHAEL JACKSON'
3C = A.replace("Michael", "Janet") # 'Janet Jackson'
4index = A.find("Jack") # 8
5not_found = A.find("XYZ") # -1
Python strings are powerful tools for handling character data. Indexing, slicing, concatenation, replication, escape sequences, and methods enable flexible and efficient string manipulation.
(4) Subtraction is not a valid operation for strings in Python.
| Concept | Description |
|---|---|
| A. Indexing | 1. Accessing characters by position |
| B. Slicing | 2. Selecting a range of characters |
| C. Escape sequence | 3. Formatting special characters |
| D. Method | 4. Function that manipulates a string |
A-1, B-2, C-3, D-4.
The method upper() returns a new string with all characters in uppercase, leaving the original string unchanged.
True. String methods return new strings and do not modify the original.