String Operations and Methods

Reading Time: 3 minutes
📝 String Operations and Methods ( Topics )

What is a String ?

Strings are one of the most important and commonly used data types in Python. They are used to store and manipulate textual data such as names, messages, and user input.

A string is a sequence of characters enclosed within quotes. In Python, strings can be created using:

  • Single quotes '...'
  • Double quotes "..."
  • Triple quotes '''...''' or """...""" (for multiline strings)

Example

# Different ways to create strings
str1 = 'Hello'
str2 = "World"
str3 = '''This is
a multiline
string'''

print(str1)
print(str2)
print(str3)

Output

Hello
World
This is
a multiline
string

String Indexing

Strings are ordered, so each character has an index starting from 0.

Example

text = "Python"

print(text[0])   # First character
print(text[3])   # Character at index 3
print(text[-1])  # Last character

Output

P
h
n

String Slicing

Slicing allows you to extract a part of the string.

Syntax:

string[start : end : step]

Example

text = "Python Programming"

print(text[0:6])     # Python
print(text[7:18])    # Programming
print(text[:6])      # From start
print(text[::2])     # Every 2nd character

Output

Python
Programming
Python
Pto rgamn

String Immutability

Strings in Python are immutable, meaning they cannot be changed after creation.

Example

text = "Hello"

# This will cause an error
# text[0] = "Y"

Output

TypeError: 'str' object does not support item assignment.

String Concatenation & Repetition

Example

str1 = "Hello"
str2 = "World"

# Concatenation
result = str1 + " " + str2

# Repetition
repeat = str1 * 3

print(result)
print(repeat)

Output

Hello World
HelloHelloHello

String Methods (Important)

Python provides many built-in methods to work with strings.

lower() and upper()

text = "Python"

print(text.lower())
print(text.upper())

Output

python
PYTHON

strip()

Removes spaces from both ends.

text = "  Hello  "
print(text.strip())

Output

Hello

replace()

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

Output

I like Python

split()

text = "apple,banana,mango"
print(text.split(","))

Output

['apple', 'banana', 'mango']

join()

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

Output

Python is fun

find()

text = "Python Programming"
print(text.find("Pro"))

Output

7

String Formatting

Used to insert variables into strings.

Example

name = "Rahul"
age = 20

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

Output

My name is Rahul and I am 20 years old

f-Strings (Modern Way)

name = "Rahul"
age = 20

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

Output

My name is Rahul and I am 20 years old

Escape Characters

Used to include special characters in strings.

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

Example

print("Hello\nWorld")
print("Hello\tWorld")
print("He said \"Hello\"")

Output

Hello
World
Hello    World
He said "Hello"

String Membership Operators

Used to check if a substring exists.

Example

text = "Python Programming"

print("Python" in text)
print("Java" not in text)

Output

True
True

Iterating Through a String

Example

text = "Python"

for char in text:
    print(char)

Output

P
y
t
h
o
n

String Length

Example

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

Output

6

Checking String Type

Example

text = "Python123"

print(text.isalpha())   # Only letters
print(text.isdigit())   # Only numbers
print(text.isalnum())   # Letters + numbers

Output

False
False
True

Reverse a String

Example

text = "Python"
print(text[::-1])

Output

nohtyP

Practice

Example

# Count vowels in a string

text = "Python Programming"
vowels = "aeiouAEIOU"
count = 0

for char in text:
    if char in vowels:
        count += 1

print("Number of vowels:", count)

Output

Number of vowels: 4
# Write a program to count words in a sentence

text = "Python is easy to learn"

words = text.split()
print(len(words))

Output

5