Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
String Special Operators in Python
Python provides several special operators for working with strings. These operators allow you to concatenate, repeat, slice, and format strings efficiently. Let's explore each operator with practical examples using string variables a = 'Hello' and b = 'Python'.
String Concatenation (+)
The + operator joins two or more strings together ?
a = 'Hello' b = 'Python' result = a + b print(result) print(a + ' ' + b)
HelloPython Hello Python
String Repetition (*)
The * operator creates multiple copies of a string ?
a = 'Hello'
print(a * 2)
print(a * 3)
print('-' * 10)
HelloHello HelloHelloHello ----------
String Indexing ([])
Square brackets access individual characters by their index position ?
a = 'Hello' print(a[0]) # First character print(a[1]) # Second character print(a[-1]) # Last character print(a[-2]) # Second last character
H e o l
String Slicing ([:])
Range slicing extracts a substring using [start:end] syntax ?
a = 'Hello' print(a[1:4]) # Characters from index 1 to 3 print(a[:3]) # First 3 characters print(a[2:]) # From index 2 to end print(a[:]) # Entire string
ell Hel llo Hello
Membership Operators (in, not in)
These operators check if a character or substring exists in a string ?
a = 'Hello'
print('H' in a) # Check if 'H' exists
print('x' in a) # Check if 'x' exists
print('M' not in a) # Check if 'M' does not exist
print('ell' in a) # Check substring
True False True True
Raw Strings (r/R)
Raw strings treat backslashes as literal characters, not escape sequences ?
# Regular string interprets \n as newline
print('Hello\nWorld')
# Raw string treats \n as literal characters
print(r'Hello\nWorld')
print(R'C:\new\path')
Hello World Hello\nWorld C:\new\path
String Formatting (%)
The % operator formats strings using placeholders ?
name = 'Alice'
age = 25
print('Name: %s, Age: %d' % (name, age))
print('Value: %.2f' % 3.14159)
print('Hello %s!' % 'World')
Name: Alice, Age: 25 Value: 3.14 Hello World!
Summary Table
| Operator | Purpose | Example | Result |
|---|---|---|---|
+ |
Concatenation | 'Hello' + 'World' |
HelloWorld |
* |
Repetition | 'Hi' * 3 |
HiHiHi |
[] |
Indexing | 'Hello'[1] |
e |
[:] |
Slicing | 'Hello'[1:4] |
ell |
in |
Membership | 'e' in 'Hello' |
True |
r/R |
Raw String | r'\n' |
\n |
% |
Formatting | 'Hi %s' % 'there' |
Hi there |
Conclusion
Python's string operators provide powerful tools for text manipulation. Use + for joining strings, * for repetition, [] for accessing characters, and in for membership testing. Raw strings with r are essential when working with file paths or regular expressions.
