Python string
Table of Contents
Description
A string in Python is a sequence of characters enclosed in single quotes ' ', double quotes " ", or triple quotes ''' ''' / """ """ for multi-line strings. Strings are immutable, meaning once created, they cannot be changed. Python provides a rich set of methods for string manipulation, including slicing, formatting, and searching.
Prerequisites
- Basic understanding of variables
- Knowledge of indexing and loops helps in string manipulation.
Examples
Here's a simple program in Python:
# String declaration s1 = "Hello" s2 = 'World' s3 = """This is a multi-line string.""" # Concatenation full = s1 + " " + s2 # Result: "Hello World" # Accessing characters print(s1[0]) # Output: 'H' (indexing starts from 0) # Slicing print(s1[1:4]) # Output: 'ell' (characters from index 1 to 3) # String methods print(s1.upper()) # Output: 'HELLO' print(s2.lower()) # Output: 'world' print(s1.replace("H", "J")) # Output: 'Jello' # Checking substring print("lo" in s1) # Output: True # Length of a string print(len(s1)) # Output: 5Real-World Applications
Processing text data (e.g., chatbots, NLP).
Reading and manipulating files (file names, extensions)
Building dynamic messages and logs.
Web scraping, parsing HTML/XML content.
Form validation (email, username, passwords).
Where topic Can Be Applied
Natural Language Processing (NLP): Tokenizing and analyzing sentences.
Web development: Handling form inputs, URLs, HTML tags.
File handling: Managing file paths and contents.
Data cleaning: Formatting and correcting data entries.
Automation scripts: Generating dynamic commands or messages.
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
What is a string in Python?
How do you declare multi-line strings?
What is string immutability? Can you modify a string in-place?
How does slicing work in strings?
Name five string methods and explain what they do.