String Basics
Introduction to Python Strings
In Python, strings are fundamental data types used to represent text. They are immutable sequences of Unicode characters, which means once a string is created, its content cannot be changed directly.
String Creation and Declaration
Basic String Declaration
## Single quotes
name = 'LabEx Python Tutorial'
## Double quotes
message = "Welcome to Python Programming"
## Multi-line strings
description = '''This is a
multi-line string
demonstration'''
String Characteristics
Immutability
Strings in Python are immutable, meaning you cannot modify individual characters after creation.
text = "Hello"
## This will raise an error
## text[0] = 'h' ## TypeError: 'str' object does not support item assignment
Indexing and Slicing
word = "Python"
## Accessing individual characters
first_char = word[0] ## 'P'
last_char = word[-1] ## 'n'
## String slicing
substring = word[1:4] ## 'yth'
String Types
String Type |
Description |
Example |
Literal Strings |
Direct text enclosed in quotes |
"Hello" |
Raw Strings |
Treat backslashes as literal characters |
r"C:\new\test" |
Unicode Strings |
Support international characters |
"こんにちは" |
String Methods
Python provides numerous built-in methods for string manipulation:
text = " LabEx Python Tutorial "
## Common string methods
print(text.strip()) ## Remove whitespace
print(text.lower()) ## Convert to lowercase
print(text.upper()) ## Convert to uppercase
print(text.replace("Python", "Programming")) ## Replace substring
Flow of String Processing
graph TD
A[String Creation] --> B[String Manipulation]
B --> C[String Output/Processing]
C --> D[Further Operations]
Memory Efficiency
Strings are stored efficiently in Python, with repeated strings often sharing the same memory reference.
a = "hello"
b = "hello"
## These might reference the same memory location
print(a is b) ## Often returns True
By understanding these fundamental concepts, you'll be well-prepared to work with strings in Python effectively.