Gyaan

Strings and String Methods

beginner strings f-strings string-methods

Strings in Python are immutable sequences of characters. Every time we “modify” a string, Python creates a brand new string object behind the scenes.

Creating Strings

single = 'hello'
double = "hello"          # same thing — pick one style and stick with it
multi = """This is a
multi-line string"""       # triple quotes for multi-line
raw = r"C:\new\folder"    # raw string — backslashes are literal

f-strings (Formatted String Literals)

Introduced in Python 3.6, f-strings are the cleanest way to embed expressions inside strings.

name = "Manish"
age = 25
print(f"Hi, I'm {name} and I'm {age} years old.")

# We can put any expression inside the braces
print(f"Next year I'll be {age + 1}")
print(f"Name uppercased: {name.upper()}")
print(f"Pi to 2 decimals: {3.14159:.2f}")  # "3.14"

String Slicing

Strings support slicing just like lists. The syntax is string[start:stop:step].

text = "Python"
print(text[0])       # 'P'
print(text[-1])      # 'n' (last character)
print(text[0:3])     # 'Pyt' (start to stop-1)
print(text[::-1])    # 'nohtyP' (reversed — classic interview question)

Essential String Methods

Here are the methods that come up the most in interviews and everyday coding:

msg = "  Hello, World!  "

# Whitespace removal
msg.strip()          # 'Hello, World!' (both sides)
msg.lstrip()         # 'Hello, World!  ' (left only)
msg.rstrip()         # '  Hello, World!' (right only)

# Case conversion
"hello".upper()      # 'HELLO'
"HELLO".lower()      # 'hello'
"hello world".title() # 'Hello World'
"hello world".capitalize()  # 'Hello world'

# Searching
"hello".find("ll")       # 2 (index of first match, -1 if not found)
"hello".index("ll")      # 2 (same but raises ValueError if not found)
"hello".startswith("he") # True
"hello".endswith("lo")   # True
"hello hello".count("hello")  # 2

# Splitting and joining
"a,b,c".split(",")       # ['a', 'b', 'c']
" ".join(["a", "b", "c"]) # 'a b c'

# Replacing
"hello world".replace("world", "Python")  # 'hello Python'

Checking String Content

These return True or False and are super handy for validation.

"123".isdigit()      # True — only digits
"abc".isalpha()      # True — only letters
"abc123".isalnum()   # True — letters or digits
"   ".isspace()      # True — only whitespace

Strings Are Immutable

This trips up a lot of people. None of the methods above change the original string — they all return a new string.

name = "hello"
name.upper()       # returns "HELLO" but name is still "hello"
name = name.upper() # now name is "HELLO" (reassigned to new object)

In simple language, always remember that string methods return new strings. If we forget to capture the return value, nothing changes.