CHAPTER 8 · TEXT DATA

Python Strings

Strings text data ko represent karti hain. Is chapter me string creation, indexing, slicing, immutability, searching, replacing, splitting, joining, cleaning, case conversion, formatting aur practical text-processing patterns samjhenge.

English + Hinglish58 min readOnline practice included

What is a string?

A Python string is an immutable sequence of Unicode characters. Single quotes, double quotes aur triple quotes se string literals create kiye ja sakte hain.

strings.pyPython
course = "Python"
message = 'Learn by practice'
multiline = """Line one
Line two"""

print(course)
print(message)
print(multiline)
Hinglish Explanation

Single aur double quotes dono normal text ke liye valid hain. Triple quotes multi-line string literals ke liye useful hote hain.

Try strings →

Quotes and escaping

Quote style wisely choose karne se escaping kam karni padti hai.

quotes.pyPython
title = "Python's Basics"
quote = 'He said "Hello"'
escaped = "He said \"Hello\""

print(title)
print(quote)
print(escaped)

Escape sequences jaise \n, \t, \\ aur escaped quotes strings ke andar special characters represent karte hain.

Raw strings

Raw string prefix r most backslashes ko literal treat karne me helpful hota hai, especially regular expressions aur Windows-style paths me.

raw.pyPython
path = r"C:\Users\Student\notes"
print(path)
Nuance: Raw strings ka trailing single backslash directly represent karna special case hai; raw strings ko “every backslash rule disappears” mat samjho.

String length with len()

len() string me characters/code points ki count return karta hai.

length.pyPython
course = "Python"
print(len(course))  # 6

Indexing

Strings zero-based indexing use karti hain. First character index 0 par hota hai.

indexing.pyPython
word = "Python"

print(word[0])   # P
print(word[1])   # y
print(word[-1])  # n
print(word[-2])  # o

Negative indexes end se count karte hain.

IndexError: Existing range ke bahar direct index access karoge to IndexError mil sakta hai.

Slicing

Slicing syntax text[start:stop] start ko include aur stop ko exclude karti hai.

slicing.pyPython
word = "BrounStack"

print(word[0:5])
print(word[5:])
print(word[:5])
print(word[-5:])

Try slicing →

Slice step and reverse

Third slice component step define karta hai.

slice-step.pyPython
text = "abcdef"

print(text[::2])   # ace
print(text[::-1])  # fedcba

[::-1] common reverse-string technique hai.

Strings are immutable

String create hone ke baad individual character in-place replace nahi kiya ja sakta.

immutable.pyPython
word = "python"

# word[0] = "P"  # TypeError
word = "P" + word[1:]
print(word)
Meaning: String methods usually new string return karti hain; original string automatically mutate nahi hoti.

Concatenation and repetition

combine.pyPython
first = "Broun"
second = "Stack"

brand = first + second
line = "-" * 20

print(brand)
print(line)

Large-scale repeated concatenation in loops ke liye join() often more suitable hota hai.

Membership with in

membership.pyPython
title = "Learn Python Fast"

print("Python" in title)
print("Java" not in title)

Membership case-sensitive hoti hai.

Case conversion methods

case.pyPython
text = "brounstack python"

print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print(text.swapcase())

Case-insensitive human text comparisons me casefold() lower() se more aggressive Unicode-aware normalization provide kar sakta hai.

Remove surrounding whitespace

strip(), lstrip() aur rstrip() outer characters remove karte hain.

strip.pyPython
name = "   Aman Verma   "

print(name.strip())
print(name.lstrip())
print(name.rstrip())
Important: strip("ab") exact substring remove nahi karta; it removes matching characters from the ends. Exact prefix/suffix ke liye removeprefix()/removesuffix() better ho sakte hain.

Prefix and suffix checks

prefix.pyPython
filename = "report.pdf"

print(filename.startswith("report"))
print(filename.endswith(".pdf"))
print(filename.removesuffix(".pdf"))

find() missing text par -1 return karta hai, while index() missing text par ValueError raise karta hai.

search.pyPython
text = "Python makes text processing practical"

print(text.find("text"))
print(text.count("t"))
print("processing" in text)

Simple existence check ke liye often in clearest hai.

Replace text

replace.pyPython
message = "I like Java"
updated = message.replace("Java", "Python")

print(message)
print(updated)

Original string unchanged rahti hai; replace() new string return karta hai.

Split a string

split() string ko pieces ki list me divide karta hai.

split.pyPython
skills = "HTML,CSS,JavaScript,Python"
parts = skills.split(",")

print(parts)
print(parts[0])

Whitespace-based split ke liye text.split() without argument repeated whitespace ko conveniently handle karta hai.

Join strings

separator.join(iterable) multiple strings ko efficiently combine karta hai.

join.pyPython
skills = ["HTML", "CSS", "Python"]
result = " | ".join(skills)

print(result)
Type rule: join() ko string elements chahiye. Numbers ko pehle string me convert karna pad sakta hai.

partition() for three parts

partition() first separator occurrence par exactly three-part tuple return karta hai.

partition.pyPython
email = "student@example.com"
name, separator, domain = email.partition("@")

print(name)
print(domain)

Useful validation methods

checks.pyPython
print("123".isdigit())
print("Python".isalpha())
print("Python3".isalnum())
print("   ".isspace())
print("hello".islower())
print("HELLO".isupper())

Ye methods input validation me useful signals de sakti hain, but real validation rules usually business context par depend karte hain.

f-strings revisited

Variables, expressions aur formatting ko readable output me combine karne ke liye f-strings useful hain.

fstrings.pyPython
name = "Aman"
score = 91.456

print(f"{name} scored {score:.2f}%")
print(f"Name length: {len(name)}")

Unicode basics

Python str Unicode text handle karta hai, so Hindi, emojis aur many world scripts directly strings me use kiye ja sakte hain.

unicode.pyPython
greeting = "नमस्ते"
emoji = "🚀"

print(greeting)
print(emoji)
Text nuance: Human-visible “character” aur Unicode code point/grapheme cluster always exactly same concept nahi hote. Beginner tasks me normal indexing sufficient hoti hai, but multilingual text processing me this distinction can matter.

str vs bytes preview

str text hai; bytes raw byte data. Encoding text ko bytes me aur decoding bytes ko text me convert karti hai.

encoding.pyPython
text = "Python"
data = text.encode("utf-8")
restored = data.decode("utf-8")

print(data)
print(restored)

Files, HTTP aur APIs me encoding later practical importance rakhegi.

Loop through a string

loop-string.pyPython
word = "Python"

for character in word:
    print(character)

Strings iterable hain, isliye for loop directly characters par iterate kar sakta hai.

Practical text-cleaning pattern

clean.pyPython
raw_name = "   aMaN verMA   "
clean_name = raw_name.strip().title()

print(clean_name)

Method chaining concise ho sakti hai, but excessively long chains readability reduce kar sakti hain.

Run cleaning example →

Performance note

Strings immutable hone ki wajah se repeated result += piece in very large loops unnecessary intermediate strings create kar sakta hai. Multiple pieces ko list me collect karke "".join(parts) often clearer and efficient pattern hai.

Common beginner mistakes

  • String index ko 1 se start assume karna.
  • Slice stop index ko inclusive samajhna.
  • Out-of-range direct indexing karna.
  • String character ko in-place assign karna.
  • String methods call karke returned value ignore karna while expecting original string to change.
  • find() aur index() behavior mix karna.
  • strip(chars) ko exact substring removal samajhna.
  • Case-sensitive comparison ko accidentally case-insensitive expect karna.
  • join() me integers directly dena.
  • Escaping/raw-string rules samjhe bina paths create karna.
  • Input normalization me password jaisi sensitive values ko unnecessarily modify karna.

Beginner best practices

  • User text ko context ke according strip() karo.
  • Exact prefix/suffix operations ke liye dedicated methods use karo.
  • Existence check ke liye readable in prefer karo.
  • Formatting ke liye f-strings use karo.
  • Multiple strings combine karne ke liye suitable jagah join() use karo.
  • Case normalization tabhi karo jab domain rules allow karte hon.
  • Original text preserve karna important ho to cleaned version separate variable me rakho.
  • Unicode text ko normal Python strings me safely handle karo; bytes conversion only when needed.

Chapter checklist

  • String creation aur quote styles clear hain?
  • Positive/negative indexing use kar sakte ho?
  • Slicing ka start/stop/step pattern samajh aaya?
  • String immutability clear hai?
  • strip(), replace(), split() aur join() use kar sakte ho?
  • find() vs in ka difference clear hai?
  • Validation methods aur f-strings use kar sakte ho?
  • str vs bytes ka basic idea samajh aaya?

Practice Task — Text Profile Cleaner

BrounStack Playground me user profile text clean aur analyze karne wala program banao.

  1. Full name input lo.
  2. Email input lo.
  3. Comma-separated skills input lo.
  4. Name par strip() use karo.
  5. Name ko readable case me convert karo.
  6. Email ko surrounding whitespace se clean karo.
  7. Email me @ present hai ya nahi check karo.
  8. partition("@") se local part aur domain nikalo.
  9. Skills ko comma par split() karo.
  10. Har skill ko clean karne ke liye loop use karo.
  11. Clean skills ko " | ".join(...) se combine karo.
  12. Name length print karo.
  13. Email domain print karo.
  14. Final profile f-string se display karo.
  15. Empty ya messy spaces ke saath different inputs test karo.

Open practice starter →