ЁЯФм
ЁЯзм
ЁЯФн
ЁЯкР
ЁЯзк
тЖР Back to Dashboard
Font Size:

1. Introduction

A string is a sequence of characters, and in Python it is one of the most frequently used data types. Strings represent text: names, addresses, sentences, passwords, file contents, and much more. Every program that communicates with a human user does so through strings, both when reading input and when displaying output. In Python, a string is written by enclosing characters in single quotes, double quotes or triple quotes, and it is stored as an immutable object of the str type.

Because strings are sequences, they support all the sequence operations: indexing, which extracts a single character, slicing, which extracts a substring, and iteration, which visits each character one by one. Strings also support the concatenation operator +, which joins two strings, and the repetition operator *, which repeats a string several times. Membership tests with the in operator check whether a character or substring exists inside a string.

Beyond these core operations, Python's str class provides a rich set of built-in methods for string processing, such as upper(), lower(), strip(), split(), join(), replace(), find() and count(). These methods make text processing concise and readable. This chapter also explains the escape characters used to represent special characters inside strings, and it applies the looping skills from the previous chapter to write character-by-character string-processing programs.

2. Creating Strings

Strings can be created by enclosing text in quotes. All three quoting styles are valid, and the choice depends on the content of the string.

s1 = 'Hello'          # single quotes
s2 = "World"          # double quotes
s3 = '''A multi-line
string'''             # triple quotes
s4 = ""               # empty string

Single and double quotes are interchangeable. Triple quotes allow strings to span multiple lines and can contain both single and double quotes. An empty string contains zero characters.

A subtle point: Python automatically concatenates adjacent string literals. For example, "Py" "thon" is the single string "Python".

3. Indexing and Slicing

Since a string is a sequence, each character has a position called an index. Python uses zero-based indexing: the first character is at index 0. Negative indices count from the end, with -1 being the last character.

word = "PYTHON"
print(word[0])    # 'P'
print(word[3])    # 'H'
print(word[-1])   # 'N'
print(word[-2])   # 'O'

Slicing extracts a substring. The slice word[start:end] returns the characters from index start up to, but not including, index end.

word = "PYTHON"
print(word[0:4])    # 'PYTH'
print(word[2:])     # 'THON'  (from 2 to end)
print(word[:3])     # 'PYT'   (from start to 2)
print(word[1:5:2])  # 'YH'    (start 1, stop 5, step 2)
print(word[::-1])   # 'NOHTYP' (reversed string)

Remember: the end index in a slice is always exclusive, and a step can be used to skip characters or reverse the string.

4. Traversing a String

Traversing means visiting each character of the string in turn. This is usually done with a for loop.

word = "Python"
for ch in word:
    print(ch, end=" ")

Traversal is the basis of many string-processing programs, such as counting vowels, counting occurrences of a letter, or checking whether a string is a palindrome.

5. String Operators

Python provides several operators that work on strings.

print("Py" + "thon")     # Python
print("Go " * 2)         # Go Go
print("Py" in "Python")  # True
print("x" not in "Python")  # True

6. Built-in Functions on Strings

Several built-in functions work with strings.

s = "hello"
print(len(s))        # 5
print(max(s))        # 'o'
print(min(s))        # 'e'
print(str(123))      # '123'

7. String Methods

Python strings have many methods that create new, processed strings. Because strings are immutable, these methods return a new string rather than modifying the original.

7.1 Case Conversion Methods

s = "hello World"
print(s.upper())      # HELLO WORLD
print(s.lower())      # hello world
print(s.title())      # Hello World
print(s.swapcase())   # HELLO wORLD

7.2 Trimming and Searching Methods

s = "  Python is fun  "
print(s.strip())           # 'Python is fun'
print("banana".count("a")) # 3
print("hello".find("l"))   # 2
print("hello".replace("l", "L"))  # heLLo

7.3 Checking and Splitting Methods

print("Hello".startswith("He"))   # True
print("123".isdigit())            # True
print("Hi there".split(" "))      # ['Hi', 'there']
print("-".join(["a", "b", "c"]))  # a-b-c

8. Escape Sequences

Escape sequences are backslash combinations that represent special characters inside a string. They allow characters that are hard to type directly.

Escape Meaning
\n Newline
\t Tab
\\ Backslash
\' Single quote
\" Double quote
print("Line1\nLine2")    # prints on two lines
print("Column1\tColumn2")
print("She said \"Hi\"")

9. Sample Programs Using Strings

9.1 Count Vowels and Consonants

s = input("Enter a sentence: ").lower()
vowels = 0
consonants = 0
for ch in s:
    if ch.isalpha():
        if ch in "aeiou":
            vowels += 1
        else:
            consonants += 1
print("Vowels:", vowels, "Consonants:", consonants)

9.2 Check if a String is a Palindrome

s = input("Enter a word: ").lower()
if s == s[::-1]:
    print("It is a palindrome")
else:
    print("It is not a palindrome")

9.3 Reverse Words in a Sentence

s = "Python is powerful"
words = s.split()
reversed_sentence = " ".join(words[::-1])
print(reversed_sentence)   # powerful is Python

Quick Revision Tables

Table 1: String Operators

Operator Operation Example Result
+ Concatenation "Py"+"thon" = "Python"
* Repetition "Ha"*3 = "HaHaHa"
in Membership "Py" in "Python" = True
not in Non-membership "x" not in "Python" = True
[] Indexing "PYTHON"[0] = 'P'
[:] Slicing "PYTHON"[1:4] = "YTH"

Table 2: Common String Methods

Method Purpose Example
upper() Convert to uppercase "hi".upper() = "HI"
lower() Convert to lowercase "HI".lower() = "hi"
strip() Remove surrounding spaces " hi ".strip() = "hi"
find(sub) Index of first occurrence "hello".find("l") = 2
count(sub) Number of occurrences "banana".count("a") = 3
split(sep) Split into list "a b".split(" ") = ['a','b']
join(list) Join list into string "-".join(["a","b"]) = "a-b"

Mind Map

flowchart TD A[Strings] --> B[Creation] B --> B1[single quotes] B --> B2[double quotes] B --> B3[triple quotes] A --> C[Access] C --> C1[Indexing] C --> C2[Slicing] C --> C3[Negative index] A --> D[Operators] D --> D1[+ Concatenation] D --> D2[* Repetition] D --> D3[in Membership] A --> E[Built-in Functions] E --> E1[len] E --> E2[max] E --> E3[min] A --> F[Methods] F --> F1[Case upper lower] F --> F2[Search find count] F --> F3[Split and Join] F --> F4[strip replace] A --> G[Escape Sequences] G --> G1[\n newline] G --> G2[\t tab]

Important Diagrams (SVG)

Diagram 1: String Indexing and Slicing

String Indexing and Slicing word = "PYTHON" P 0 Y 1 T 2 H 3 O 4 N 5 -6 -5 -4 -3 -2 -1 word[0:4] = "PYTH" end index 4 is exclusive [::-1] reverses string Negative indices count from the end; -1 is the last character. Golden Rule: Indexing uses zero-based positive indices and negative indices from the end; slices exclude the stop index.

Diagram 2: String Processing Pipeline

Processing Text with String Methods Original " Hello World " strip() "Hello World" lower() "hello world" split(" ") ['hello', 'world'] join("-") "hello-world" Strings are immutable: each method returns a new string; the original stays unchanged. Golden Rule: String methods do not modify the original; capture their return values by assigning or printing them.

Common Mistakes

  1. Off-by-one errors in slicing: word[0:4] gives 4 characters, indices 0 to 3. The stop index is always exclusive.
  2. Trying to modify a character: word[0] = 'X' raises a TypeError because strings are immutable.
  3. Confusing find() with index(): find() returns -1 when the substring is absent, while index() raises a ValueError.
  4. Forgetting that methods return new strings: Calling upper() without assigning or printing the result silently discards the transformed string.
  5. Using isalpha() on a string with spaces: isalpha() returns False if the string contains spaces or digits; it checks only letters.
  6. Slicing with start > stop by default: word[5:2] returns an empty string unless a negative step is given.
  7. Comparing strings case-sensitively: "Python" == "python" is False because their characters differ in case.
  8. Misusing split and join: split needs a separator argument if the default whitespace is not desired, and join expects a list of strings.

Exam Tips

  1. Practise slicing with various combinations including negative indices and step, because these are frequently tested.
  2. Memorise the difference between find() (-1 if absent) and index() (raises error) as it appears in objective questions.
  3. Know the outputs of upper, lower, strip, split, join and replace for short-answer questions.
  4. Remember strings are immutable; this is a recurring one-mark question.
  5. Be able to write programs that count vowels, reverse a string, check a palindrome and count occurrences of a character.
  6. Learn escape sequences \n and \t and use them correctly in output formatting questions.
  7. Use the membership operator in for substring checks; it is concise and frequently required.

Conclusion

Strings are the primary way Python represents and processes text, and they combine the simplicity of a sequence with a powerful library of methods. Indexing and slicing provide precise access to characters and substrings, operators such as concatenation, repetition and membership build and inspect strings, and the extensive set of methods handles case conversion, searching, trimming, splitting and joining with ease. Because strings are immutable, every operation returns a new string, which is a crucial fact for correct programming. With strings mastered, the next chapter turns to lists, Python's most flexible data structure, which shares many of the sequence concepts introduced here.