String Operations in Python | Python Tutorial - Learn with VOKS
Back Next

String Operations in Python


A string is a sequence of characters (letters, numbers, symbols, spaces) enclosed in quotes.

name = "Danny"
message = 'Hello World'

You can use:

  • Single quotes ' '
  • Double quotes " "
  • Triple quotes ''' ''' or """ """ (for multi-line text)

Basic String Operations

1️⃣ Concatenation (Joining Strings)

Combining two or more strings using +.

first = "Hello"
second = "World"

result = first + " " + second
print(result)

Output:

Hello World

2️⃣ Repetition

Repeat a string using *.

word = "Hi "
print(word * 3)

Output:

Hi Hi Hi

3️⃣ Indexing (Accessing Characters)

Each character has a position (index).

text = "Python"
print(text[0])   # First character
print(text[-1])  # Last character

📊 Index Table

| Character | P | y | t | h | o | n |
|-----------|---|---|---|---|---|---|
| Index     | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative  | -6|-5 |-4 |-3 |-2 |-1 |

4️⃣ Slicing (Getting Part of a String)

text = "Python Programming"

print(text[0:6])   # Python
print(text[7:18])  # Programming
print(text[:6])    # Python
print(text[7:])    # Programming

Useful String Functions (Methods)

Common String Methods

| Method | Description | Example |
|--------|------------|---------|
| lower() | Converts to lowercase | "PYTHON".lower() → python |
| upper() | Converts to uppercase | "python".upper() → PYTHON |
| title() | Capitalizes each word | "hello world".title() |
| capitalize() | Capitalizes first letter | "python".capitalize() |
| strip() | Removes spaces from both ends | " hi ".strip() |
| lstrip() | Removes left spaces | " hi".lstrip() |
| rstrip() | Removes right spaces | "hi ".rstrip() |

5️⃣ Replacing Text

text = "I like Java"
print(text.replace("Java", "Python"))

Output:

I like Python

6️⃣ Splitting Strings

Convert a string into a list.

sentence = "Python is fun"
print(sentence.split())

Output:

['Python', 'is', 'fun']

7️⃣ Joining Strings

words = ['Python', 'is', 'fun']
print(" ".join(words))

Output:

Python is fun

String Checking Methods

These return True or False.

| Method | Meaning | Example |
|--------|---------|---------|
| isalpha() | Only letters | "Python".isalpha() |
| isdigit() | Only numbers | "123".isdigit() |
| isalnum() | Letters & numbers | "Python3".isalnum() |
| islower() | All lowercase | "python".islower() |
| isupper() | All uppercase | "PYTHON".isupper() |
| startswith() | Begins with | "Hello".startswith("H") |
| endswith() | Ends with | "Hello".endswith("o") |

Finding Text in a String

text = "I love Python"

print(text.find("Python"))   # Returns position
print(text.count("o"))       # Counts occurrences

String Length

text = "Python"
print(len(text))

String Formatting (Very Important )

1. Using f-strings

name = "Danny"
age = 25

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

2. Using format()

print("My name is {} and I am {}".format(name, age))

Escape Characters

Used for special formatting.

| Escape | Meaning |
|--------|---------|
| \n | New line |
| \t | Tab |
| \\ | Backslash |
| \" | Double quote |
| \' | Single quote |

Example:

print("Hello\nWorld")

Multiline Strings

text = """This is
a multiline
string"""

Membership Operators

Check if a value exists in a string.

text = "Python"

print("P" in text)      # True
print("Java" not in text)  # True

Examples

Example 1: User Input Formatter

name = input("Enter your name: ").strip().title()
print(f"Welcome {name}")

Example 2: Email Checker

email = input("Enter email: ")

if "@" in email and "." in email:
    print("Valid email")
else:
    print("Invalid email")
Python
Intorduction Python Syntax Compare to other Programming Languages How to Install Python Print Statement Python Comments Data Structure and Data Type String Operations in Python Simple Input and Output Simple Output Formatting
All Courses
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL