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 Data Type in Python
Strings in Python are identified as a contiguous set of characters represented in quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator [ ] and [:] with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.
String Creation
You can create strings using single quotes, double quotes, or triple quotes for multi-line strings ?
# Different ways to create strings single_quote = 'Hello World!' double_quote = "Hello World!" multi_line = """This is a multi-line string""" print(single_quote) print(double_quote) print(multi_line)
Hello World! Hello World! This is a multi-line string
String Indexing and Slicing
Strings support indexing and slicing operations. Positive indices start from 0, while negative indices start from -1 ?
text = 'Hello World!' print(text) # Prints complete string print(text[0]) # Prints first character print(text[2:5]) # Prints characters from index 2 to 4 print(text[2:]) # Prints string starting from 3rd character print(text[-1]) # Prints last character print(text[-6:-1]) # Prints characters using negative indexing
Hello World! H llo llo World! ! World
String Operations
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator ?
text = 'Hello World!'
print(text * 2) # Prints string two times
print(text + " TEST") # Prints concatenated string
print("Python " * 3) # Repetition with different string
Hello World!Hello World! Hello World! TEST Python Python Python
String Properties
Strings in Python are immutable, meaning you cannot change individual characters. You can check string length and membership ?
text = 'Hello World!'
print(len(text)) # String length
print('Hello' in text) # Membership test
print('Python' in text) # Membership test
print(text.upper()) # Convert to uppercase
print(text.lower()) # Convert to lowercase
12 True False HELLO WORLD! hello world!
Escape Characters
Use backslash \ to include special characters in strings ?
# Examples of escape characters
print("She said, "Hello!"") # Double quotes inside string
print('It's a beautiful day') # Single quote inside string
print("Line 1\nLine 2") # New line
print("Column 1\tColumn 2") # Tab character
She said, "Hello!" It's a beautiful day Line 1 Line 2 Column 1 Column 2
Conclusion
Python strings are immutable sequences that support indexing, slicing, concatenation, and repetition. Use single or double quotes for simple strings, and triple quotes for multi-line strings. Remember that string indexing starts at 0.
