⚡0 XP🔥0

Strings

Lesson 13 of 33 ⏱ 4 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Create strings, access characters with indexing, extract parts with slicing, join and repeat strings, and understand why strings are immutable.

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#

▶ Try it YourselfPython
Ctrl + Enter to run

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
▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

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.
▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

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)
Did you know?

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:

▶ Try it YourselfPython
Ctrl + Enter to run

Joining and repeating#

Operation Example Result
Concatenation + "Good" + " " + "Morning" "Good Morning"
Repetition * "-" * 10 "----------"
Membership in "gram" in "program" True
Comparison "apple" < "banana" True (alphabetical)
▶ Try it YourselfPython
Ctrl + Enter to run

Looping through a string#

▶ Try it YourselfPython
Ctrl + Enter to run

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):

▶ Try it YourselfPython
Ctrl + Enter to run

Summary#

  • Strings are sequences of characters in '...', "..." or """...""".
  • len(s) gives the length; indexes run from 0 to len(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, in checks for a substring.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

First and last character

Read a word and print its first character and last character separated by a space.

Test input:
Vindhya
Expected output:
V a
2

Palindrome check

Read a word and print Palindrome if it reads the same backwards, otherwise Not palindrome. (Ignore case - Madam is a palindrome.)

Test input:
Madam
Expected output:
Palindrome
3

Mask a mobile number

Read a 10-digit mobile number and print it with only the last 4 digits visible: ******3210 for 9876543210.

Test input:
9876543210
Expected output:
******3210

Quick Quiz

Q1.

If s = "PYTHON", what is s[-1]?

Q2.

If s = "PYTHON", what is s[1:4]?

Q3.

What does "abc"[::-1] give?

Q4.

What is len("Hello World")?

Q5.

What happens with s = "cat"; s[0] = "b"?