In Python, strings are sequences of characters enclosed within single quotes ('
), double quotes ("
) or triple quotes ('''
or """
). Strings are one of the most commonly used data types in Python.
Creating Strings
You can create strings using:
- Single quotes
- Double quotes
- Triple quotes (used for multi-line strings or documentation strings).
Examples:
# Single Quotes
string1 = 'Hello, World!'
# Double Quotes
string2 = "Python is fun!"
# Triple Quotes (Multi-line String)
string3 = '''This is a multi-line
string in Python.'''
print(string1) # Output: Hello, World!
print(string2) # Output: Python is fun!
print(string3)
# Output:
# This is a multi-line
# string in Python.
Accessing Strings
Strings are indexed and can be accessed using their position.
- Indexing starts at
0
(left to right). - Negative indexing starts at
-1
(right to left).
Example:
text = "Python"
# Positive Indexing
print(text[0]) # Output: P
print(text[3]) # Output: h
# Negative Indexing
print(text[-1]) # Output: n
print(text[-4]) # Output: t
String Slicing
You can extract portions of a string using slicing. The syntax is:
string[start:stop:step]
start
: Starting index (inclusive).stop
: Ending index (exclusive).step
: Step size (default is1
).
Examples:
text = "Python Programming"
# Slice from index 0 to 5
print(text[0:6]) # Output: Python
# Slice with step
print(text[0:12:2]) # Output: Pto rg
# Omitting start (default is 0)
print(text[:6]) # Output: Python
# Omitting stop (default is end of string)
print(text[7:]) # Output: Programming
# Using negative index
print(text[-11:]) # Output: Programming
String Properties
- Immutable: Strings cannot be changed after creation.
Example:text = "hello" text[0] = 'H' # Error: 'str' object does not support item assignment
- Concatenation: Use
+
to combine strings.
Example:str1 = "Hello" str2 = "World" print(str1 + " " + str2) # Output: Hello World
- Repetition: Use
*
to repeat strings.
Example:text = "Hi! " print(text * 3) # Output: Hi! Hi! Hi!
Common String Methods
Python provides many built-in methods for string manipulation. Here are some frequently used methods:
Method | Description | Example |
---|---|---|
upper() | Converts string to uppercase. | "hello".upper() → "HELLO" |
lower() | Converts string to lowercase. | "HELLO".lower() → "hello" |
title() | Converts to title case (capitalize each word). | "hello world".title() → "Hello World" |
strip() | Removes leading/trailing spaces. | " hello ".strip() → "hello" |
replace() | Replaces a substring with another. | "abc".replace('a', 'z') → "zbc" |
split() | Splits string into a list of words. | "a,b,c".split(',') → ['a', 'b', 'c'] |
join() | Joins elements of a list into a single string. | ",".join(['a', 'b', 'c']) → "a,b,c" |
find() | Returns index of first occurrence of substring. | "hello".find('l') → 2 |
startswith() | Checks if string starts with a specific substring. | "Python".startswith("Py") → True |
endswith() | Checks if string ends with a specific substring. | "Python".endswith("on") → True |
String Formatting
Python provides ways to format strings dynamically:
- Using f-strings (Python 3.6+):
name = "Alice" age = 25 print(f"My name is {name} and I am {age} years old.") # Output: My name is Alice and I am 25 years old.
- Using
.format()
method:name = "Bob" print("My name is {}.".format(name)) # Output: My name is Bob.
- Using
%
operator:name = "Eve" age = 30 print("My name is %s and I am %d years old." % (name, age)) # Output: My name is Eve and I am 30 years old.
Escape Characters
Escape characters allow you to include special characters in strings.
Escape Character | Description | Example |
---|---|---|
\\ | Backslash | "This is a \\\\" |
\' | Single Quote | 'It\'s great!' |
\" | Double Quote | "He said \"Hi\"" |
\n | New Line | "Hello\nWorld" |
\t | Tab Space | "Hello\tWorld" |
\b | Backspace | "AB\bC" → "AC" |
String Operations
- Checking for Substrings:
text = "Hello, World!" print("Hello" in text) # Output: True print("Python" not in text) # Output: True
- Iterating Through Strings:
for char in "Python": print(char) # Output: # P # y # t # h # o # n
- String Length: Use
len()
to get the number of characters in a string:text = "Hello" print(len(text)) # Output: 5
Practical Examples
Example 1: Reversing a String
text = "Python"
reversed_text = text[::-1] # Slice with step -1
print(reversed_text) # Output: nohtyP
Example 2: Count Vowels in a String
text = "Programming is fun!"
vowels = "aeiouAEIOU"
count = sum(1 for char in text if char in vowels)
print("Number of vowels:", count) # Output: Number of vowels: 5
Example 3: Capitalize Each Word
text = "hello world"
print(text.title()) # Output: Hello World
Summary
- Strings are immutable sequences of characters in Python.
- Use indexing and slicing to access portions of a string.
- String methods help in formatting, modifying, and analyzing strings.
- Use escape sequences for special characters.
- Strings can be formatted dynamically using
f-strings
,.format()
, or%
operator.
This explanation covers Python strings with detailed examples and practical use cases.