Lesson 9 of 18 · 2 min
Strings — Working with Text in Detail
Creating Strings — Multiple Ways
name = "Priya Sharma" # double quotes city = 'Chennai' # single quotes (identical to double) sentence = "It's a great day" # single quote INSIDE double quotes — fine message = 'He said "hello"' # double quotes INSIDE single quotes — fine multi = """Line one Line two Line three""" # triple quotes for multi-line strings
String Length — len()
word = "Python" # 6-character string print(len(word)) # count the characters: P-y-t-h-o-n = 6 sentence = "Hello World" # 11 characters (the space counts!) print(len(sentence)) # count all characters including space
Output: 6 11
String Indexing — Accessing Individual Characters
A string is like a row of numbered boxes:
P y t h o n [0] [1] [2] [3] [4] [5] ← positive indexes (left to right, starting at 0) [-6] [-5] [-4] [-3] [-2] [-1] ← negative indexes (right to left, starting at -1)
word = "Python" # 6-character string print(word[0]) # first character (index starts at ZERO, not one) print(word[1]) # second character print(word[5]) # last character (index = length - 1 = 6 - 1 = 5) print(word[-1]) # last character using negative index (same as [5]) print(word[-2]) # second-to-last character
Output: P y n n o
String Slicing — Extracting a Portion
Syntax: string[start:stop:step]
start: where to begin (this position IS included)stop: where to end (this position is NOT included — stop early!)step: how many positions to jump (default is 1)
text = "Hello, World!" # 13-character string print(text[0:5]) # characters from index 0 to 4 (stop=5 is excluded) print(text[7:12]) # characters from index 7 to 11 print(text[:5]) # from the very beginning up to (not including) index 5 print(text[7:]) # from index 7 all the way to the end print(text[::2]) # every second character (jump 2 each time) print(text[::-1]) # step of -1 = go backwards = reverses the string
Output: Hello World Hello World! Hlo ol! !dlroW ,olleH
