String in Python — Complete Guide (Slicing, Methods, f-Strings & More)

August 02, 2025   4 Min Read 31

What You’ll Learn in This Blog

  • What are strings and how to create them
  • String indexing and slicing
  • Common string methods
  • String formatting (f-strings, .format())
  • Escape characters and raw strings
  • Best practices

What is a String in Python?

A string is a sequence of characters enclosed in single, double or triple quotes.


name = "Akash"
greeting = 'Hello'
multiline = """This 
is 
a multi-line string."""

String Indexing

Each character in a string has an index (starting at 0).


word = "Python"
print(word[0])  # P
print(word[5])  # n

You can use negative indexing too:


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

String Slicing

Slicing returns a substring:


word = "Python"
print(word[0:3])   # Pyt
print(word[:4])    # Pyth
print(word[2:])    # thon
print(word[-3:])   # hon

Syntax: string[start:end:step]


print(word[::2])   # Pto (skip every 2nd char)

Common String Methods

Here are the most useful string methods:

MethodDescription
lower()Converts to lowercase
upper()Converts to uppercase
capitalize()Capitalizes first letter
strip()Removes whitespace
replace(a, b)Replaces a with b
split()Splits into a list
join()Joins list into string
startswith()Checks if string starts with value
endswith()Checks if string ends with value
find()Returns index of first match
count()Counts number of times substring appears

Example:


text = "  Python is awesome  "
print(text.strip().upper().replace("AWESOME", "POWERFUL"))
# Output: PYTHON IS POWERFUL

f-Strings (Formatted Strings)

f-strings provide a readable way to embed expressions inside strings using {}.


name = "Akash"
age = 25
print(f"My name is {name} and I am {age} years old.")

Other way to format strings:


# .format()
print("Hello {}, your score is {}".format("Akash", 95))

# % formatting (older)
print("Your balance is %.2f" % 123.456)

Multiline Strings


message = """Dear Akash,
Welcoe to python!
"""
print(message)

Escape Characters

Use \ for special characters:

EscapeMeaning
\nNew line
\tTab
\\Backslash
\'Single quote
\"Double quote

print("He Said, \"Python is fun!\"")

Raw Strings

Prefix r to disable escape characters:


print(r"C:\Users\Akash\Documents")  # No \n interpreted

Strings Are Immutable

You cannot change a character in a string:


text = "hello"
# text[0] = 'H' ❌ will raise an error

Instead, create a new string:


text = "H" + text[1:]  # Hello

Summary

FeatureExample
Indexing"Python"[0] → P
Slicing"Python"[1:4] → yth
Methods"abc".upper() → ABC
f-Stringsf"Hi {name}"
Escape chars\n, \t, \"
ImmutabilityStrings cannot be modified in-place

Task

  1. Take a user’s full name and:
    • Capitalize the first letter of each word.
    • Count the total characters (excluding spaces).
    • Replace all "a" with "@"

Input: akash kumar
Output: Akash Kumar | Total: 10 | Modified: Ak@sh Kum@r

Leave a Reply