⬅ Previous Next ➡

Strings and Handling

String Creation in Python
  • String is a sequence of characters.
  • Can be created using single quotes, double quotes, or triple quotes.
s1 = "Python"
s2 = 'Hello'
s3 = """Multi-line
string"""
print(s1, s2)
print(s3)
String Indexing
  • Each character has an index starting from 0.
  • Negative index starts from -1 (last character).
text = "PYTHON"

print(text[0])    # P
print(text[3])    # H
print(text[-1])   # N
print(text[-2])   # O
String Slicing
  • Slicing format: str[start:stop:step]
  • stop is excluded (up to stop-1).
txt = "PYTHON PROGRAMMING"

print(txt[0:6])       # PYTHON
print(txt[7:18])      # PROGRAMMING
print(txt[:6])        # PYTHON
print(txt[7:])        # PROGRAMMING
print(txt[::2])       # PTONPORMIG
print(txt[::-1])      # reverse
String Methods (Common)
  • lower(), upper(), title(), capitalize()
  • strip(), lstrip(), rstrip()
  • replace(), split(), join()
  • startswith(), endswith()
s = "  Python Programming  "

print(s.lower())
print(s.upper())
print(s.strip())
print(s.replace("Python", "Java"))
print("a,b,c".split(","))
print("-".join(["A", "B", "C"]))
String Formatting (f-string, format, %)
  • f-string is the easiest and most used.
  • format() and % formatting are also supported.
name = "Sourav"
age = 25
pi = 3.14159

print(f"Name: {name}, Age: {age}")
print("Name: {}, Age: {}".format(name, age))
print("Pi = %.2f" % pi)
Concatenation and Repetition
  • + joins strings (concatenation).
  • * repeats strings.
a = "Hello"
b = "World"

print(a + " " + b)     # Hello World
print("Hi! " * 3)      # Hi! Hi! Hi!
String Immutability
  • Strings are immutable (cannot be changed in-place).
  • If you modify, Python creates a new string.
s = "Python"
# s[0] = "J"   # Error (cannot modify)

s2 = "J" + s[1:]
print(s2)        # Jython
Searching in Strings
  • in checks substring existence.
  • find() returns index (or -1 if not found).
  • index() returns index (error if not found).
  • count() counts occurrences.
text = "python programming"

print("python" in text)         # True
print(text.find("prog"))        # 7
print(text.count("m"))          # 2
String Comparison
  • Strings are compared lexicographically (dictionary order).
  • Comparison is case-sensitive.
a = "Apple"
b = "Banana"
c = "apple"

print(a == b)     # False
print(a < b)      # True
print(a == c)     # False
Escape Characters in Strings
  • \n new line
  • \t tab
  • \" double quote
  • \' single quote
  • \\ backslash
print("Hello\nWorld")
print("A\tB\tC")
print("He said: \"Python\"")
print('It\'s Python')
print("C:\\Users\\Admin")
⬅ Previous Next ➡