Overview:
- Strings are used for representing and processing texts of arbitrary length.
- In other programming languages like C, C++ and Java there is a separate type representing characters. In those languages strings are collection of characters.
- In Python there is no separate type to represent characters.
- Python strings are a collection of code points.
- In Python, individual characters as well, are represented as strings.
- Strings are immutable in Python.
- Strings in Python are of type str which is a built-in class in Python.
String Construction:
Strings literals can be constructed in multiple ways using:
- Single quotes
- Double quotes
- Triple quotes
- Constructor
Single Quoted Python Strings Vs Double Quoted Python Strings:
In Python, there is no difference between strings constructed using single quotes and double quotes. It is good if the developer could stick to one convention.
If a string contains a single quote or double quote - use the other one to avoid escaping it with a backslash, which improves readability.
Triple Quoted Strings:
Triple quoted strings are used to provide string literals that span across multiple lines in a Python Program. All the white spaces are taken as part of the string literal. Triple quoted strings are also used as docstrings in a Python Program.
Using str constructor:
The str constructor function takes a collection of unicode points(ie., characters) enclosed by single/double/triple quotes.
Another variant of the str() constructor takes encoding and the error handling scheme as parameters to it.
Example:
sampleString = str("Universe is Big")
# Convert the string to lower case lowerCase = sampleString.lower() print("String converted to lower case:{}".format(lowerCase))
# Capitalize only the first letter capitalized = sampleString.capitalize() print("String with first letter capitalized:{}".format(capitalized))
# Find the length of the string stringLength = len(sampleString) print("String length:{}".format(stringLength))
# Check if all the characters all alphabets alphaCheck = sampleString.isalpha()
# False as the string has space characters print("All the characters all alphabets:{}".format(alphaCheck))
|
Output:
String converted to lower case:universe is big String with first letter capitalized:Universe is big String length:15 All the characters all alphabets:False |
String Methods:
The str class in Python provides a collection of methods to process strings. The str methods are listed here as a table.
Method Name |
Responsibility |
Returns a copy of the string instance with the following modifications done
|
|
|
|
|
|
|
|
encode(encoding="utf-8", errors="strict") |
Present in the string. |
|
|
find(sub[, start[, end]]) |
|
index(sub[, start[, end]]) |
|
isalnum() |
|
|
|
isidentifier() |
|
islower() |
|