Tuesday, 8 July 2025

Strings and String Operations in Python

Strings and String Operations in Python

🔶 What is a String?

A string is a sequence of characters enclosed in single quotes ('), double quotes ("), or even triple quotes (''' or """).

✅ Examples:

text1 = 'Hello'
text2 = "Python"
text3 = '''Data Science'''

A string can contain:

  • Letters: 'abc'
  • Numbers: '123' (as characters)
  • Symbols: '@#$'
  • Spaces: 'Data Science'

In Python, a string is immutable, meaning once it's created, it cannot be changed.

🔶 How to Create a String

🔸 Using quotes:

name = "Alice"
greeting = 'Hello!'

🔸 Using str() constructor:

number = 123
string_number = str(number)   # '123'

🔶 String Indexing and Slicing

✅ Indexing:

Each character in a string has a position called an index. Indexing starts from 0.

word = "Python"
print(word[0])   # 'P'
print(word[3])   # 'h'

You can also use negative indexing:

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

✅ Slicing:

Slicing means getting a part of the string.

word = "DataScience"
print(word[0:4])   # 'Data'
print(word[4:])    # 'Science'
print(word[:4])    # 'Data'
print(word[::2])   # 'Dt cec' (skips every second character)

🔶 Basic String Operations

Operation Syntax / Example Description
Concatenation "Data" + "Science" Joins two strings → 'DataScience'
Repetition "Python" * 3 Repeats string → 'PythonPythonPython'
Length len("Python") Returns number of characters → 6
Membership 'D' in "Data" Checks if character exists → True
Looping for char in "AI": print(char) Iterates over characters

🔶 String Methods (Built-in Functions)

Python provides many helpful functions (methods) to work with strings.

🟩 Common String Methods

Method Description Example
.lower() Converts to lowercase 'PYTHON'.lower() → 'python'
.upper() Converts to uppercase 'data'.upper() → 'DATA'
.title() Capitalizes each word 'machine learning'.title()
.strip() Removes spaces from both ends ' data '.strip() → 'data'
.replace(old, new) Replaces a part of the string 'AI'.replace('A','I')
.split(separator) Splits string into list 'a,b,c'.split(',') → ['a','b','c']
.join(list) Joins list into string ','.join(['a','b','c']) → 'a,b,c'
.find(substring) Finds first index of substring 'python'.find('t') → 2
.count(substring) Counts how many times a substring appears 'banana'.count('a') → 3
.startswith(sub) Checks if string starts with sub 'hello'.startswith('he') → True
.endswith(sub) Checks if string ends with sub 'file.txt'.endswith('.txt') → True

🔶 Escape Characters

Escape characters are used to include special characters in strings.

Escape Code Description Example Output
\n New line Line 1
Line 2
\t Tab (space) Adds tab space
\' Single quote It's Python
\" Double quote He said "Hi"
\\ Backslash \
print("Hello\nWorld")      # prints on two lines
print("She said, \"Yes\"") # uses double quotes inside string

🔶 String Formatting

Used to insert variables into strings.

✅ 1. Using f-strings (Modern & Preferred)

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

✅ 2. Using format()

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

🟦 Real-life Applications in Data Science

Task How Strings Help
Reading file content File data is read as strings
Preprocessing text (NLP) Clean and format input strings
Parsing CSV/JSON/XML data Split and analyze text-based files
Converting input values Convert raw strings to usable formats
Displaying messages or dashboards Present data using formatted strings

🧠 Key Points to Remember

  • Strings are sequences of characters and are immutable.
  • You can use indexing and slicing to access parts of a string.
  • There are many built-in string methods to manipulate text.
  • Strings can be formatted using f-strings or .format().
  • Strings play a key role in file handling, web scraping, NLP, and more.

📝 Practice Questions

  1. Take a sentence from user input and count how many words it has.
  2. Write a program to reverse a string using slicing.
  3. Ask the user to enter a name, and check if it starts with a capital letter.
  4. Replace all spaces in a sentence with underscores (_).
  5. Check if a string is a palindrome (same forward and backward).

No comments:

Post a Comment

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...