Python String Tutorial – Complete Guide for Developers

Share this post on:

Strings in Python are one of the most widely used data types. They represent text and offer powerful built-in methods for manipulation. This guide is short, point-to-point, and covers almost everything a developer needs.

Basics of Python Strings

s = "Hello, World!"
print(type(s))   # <class 'str'>
  • Strings are sequences of Unicode characters.
  • Can be enclosed in 'single', "double", or '''triple''' quotes.

String Creation

a = 'single'
b = "double"
c = '''multi-line
string'''

Accessing & Slicing

s = "Python"
print(s[0])     # P
print(s[-1])    # n
print(s[0:4])   # Pyth
print(s[::-1])  # nohtyP (reverse)

String Operations

s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Concatenation
print(s1 * 3) # Repetition
print("H" in s1) # Membership

String Methods (Cheat Sheet)

s = "  Python Strings  "

# Case
s.lower()       # '  python strings  '
s.upper()       # '  PYTHON STRINGS  '
s.title()       # '  Python Strings  '
s.capitalize()  # '  python strings  '

# Trim & Replace
s.strip()             # "Python Strings"
s.replace("Python", "Java")

# Search
s.startswith("Py")    # False
s.endswith("gs")      # True
s.find("Strings")     # 9
s.count("t")          # 2

# Split & Join
s.split()             # ['Python', 'Strings']
"-".join(["A", "B"])  # 'A-B'

# Alignment
"hi".center(10, "-")  # '----hi----'

# Check Type
"123".isdigit()       # True
"abc".isalpha()       # True
"abc123".isalnum()    # True

String Formatting

name, age = "Alice", 25

# Old style
print("Name: %s, Age: %d" % (name, age))

# str.format()
print("Name: {}, Age: {}".format(name, age))

# f-string (Python 3.6+)
print(f"Name: {name}, Age: {age}")

Raw Strings & Escape Sequences

print("Line1\nLine2")  # Newline
print(r"Line1\nLine2") # Raw string, prints \n

String Immutability

s = "hello"
# s[0] = "H" ❌ Error
s = "H" + s[1:]  # ✅ Workaround

String Slicing in Python

Slicing lets you extract substrings using the syntax:

s[start:end:step]
  • start: index to begin (default = 0)
  • end: index to stop (excluded, default = len(s))
  • step: interval between indices (default = 1)
s = "PythonStrings"

print(s[0:6])      # 'Python'   → from index 0 to 5
print(s[7:])       # 'Strings'  → from index 7 to end
print(s[:6])       # 'Python'   → from start to index 5
print(s[-7:])      # 'Strings'  → using negative index
print(s[::2])      # 'PtoSrn'   → every 2nd char
print(s[::-1])     # 'sgnirtSnothyP' → reverse string

👉 Key Points:

  • Negative indices count from the end (-1 = last char).
  • Omitting start or end defaults to full length.
  • Using [::-1] is a Pythonic way to reverse strings.

Advanced Usage

# Unicode
u = "\u03A9"   # Ω

# Encoding/Decoding
s = "Python"
b = s.encode("utf-8")  # b'Python'
print(b.decode("utf-8"))

# String interpolation with dict
data = {"lang": "Python", "ver": 3}
print("I code in {lang} v{ver}".format(**data))

Quick Reference (Cheet Sheet)

  • Creation: ', ", ''' '''
  • Access: s[i], slicing [start:end:step]
  • Concat/Repeat: +, *
  • Check: .isdigit(), .isalpha(), .isalnum()
  • Modify: .strip(), .replace(), .lower(), .upper()
  • Search: .find(), .count(), .startswith(), .endswith()
  • Split/Join: .split(), .join()
  • Format: %, .format(), f""
  • Raw/Unicode: r"", \uXXXX

✅ Conclusion

Python strings are immutable, versatile, and powerful. With built-in methods and formatting options, they cover everything from simple text manipulation to advanced encoding. Mastering string operations boosts productivity in real-world projects.

Share this post on:

Leave a Reply

Your email address will not be published. Required fields are marked *