What is a string?#
A string (str) is a sequence of characters - letters, digits, spaces, symbols, even emojis and Hindi text. Strings are written inside quotes:
a = 'single quotes'
b = "double quotes"
c = """triple quotes
can span many lines"""
d = "नमस्ते"
Single and double quotes work the same. Choose the one that avoids conflict with quotes inside the text:
msg1 = "It's a sunny day" # apostrophe inside double quotes
msg2 = 'He said "Hello"' # double quotes inside single quotes
msg3 = "He said \"Hello\"" # or escape with a backslash
Length of a string#
Indexing - getting one character#
Each character has a position number called an index. Indexes start at 0. Negative indexes count from the end.
String: P Y T H O N
Index: 0 1 2 3 4 5
Negative:-6 -5 -4 -3 -2 -1
Using an index that doesn't exist gives IndexError: string index out of range. For "PYTHON" (length 6), the last valid index is 5, not 6.
Slicing - getting a part of a string#
string[start : stop : step]
start- where to begin (included). Default: beginning.stop- where to end (not included). Default: end.step- how many to jump. Default: 1.
Slicing मतलब string का एक टुकड़ा काटना। s[start:stop] लिखने पर:
startवाला index शामिल होता है,stopवाला index शामिल नहीं होता।
जैसे "PROGRAMMING"[0:3] में index 0, 1, 2 आते हैं → "PRO"। Index 3 नहीं आता।
कुछ shortcut याद रखें:
s[:4]→ शुरू से पहले 4 अक्षरs[-4:]→ आखिरी 4 अक्षरs[::-1]→ पूरी string उल्टी (reverse)
Slicing never gives an IndexError - "abc"[1:100] simply returns "bc".
Strings are immutable#
You can't change a character inside an existing string:
name = "ravi"
name[0] = "R" # TypeError: 'str' object does not support item assignment
Instead, build a new string:
Joining and repeating#
| Operation | Example | Result |
|---|---|---|
Concatenation + |
"Good" + " " + "Morning" |
"Good Morning" |
Repetition * |
"-" * 10 |
"----------" |
Membership in |
"gram" in "program" |
True |
| Comparison | "apple" < "banana" |
True (alphabetical) |
Looping through a string#
Multi-line strings and raw strings#
address = """Vindhyaedu Institute
MG Road, Indore
Madhya Pradesh"""
print(address)
path = r"C:\new\test" # r = raw string: backslashes are not escape codes
print(path) # C:\new\test
Character codes: ord() and chr()#
Every character has a number (Unicode code point):
Summary#
- Strings are sequences of characters in
'...',"..."or"""...""". len(s)gives the length; indexes run from0tolen(s) - 1, negatives from the end.- Slicing
s[start:stop:step]- stop is excluded;s[::-1]reverses. - Strings are immutable - create new strings instead of editing.
+joins,*repeats,inchecks for a substring.