Definition
- In Python, a string is a sequence of characters enclosed within single (‘ ‘), double (” “), or triple quotes (”’ ”’ or “”” “””).
- Strings are immutable, i.e. they cannot be changed after creation.
- Strings in Python are powerful and come with many built-in methods for manipulation.
String Creation/Declaration
- We can define strings using:-
Accessing Characters in a String
- Strings in Python are indexed and support slicing features.
- For example –
String Operations
- Python provides several operations on strings:-
a) Concatenation (+)
b) Repetition (*)
c) Membership (in
, not in
)
Built-in String Methods
- Python provides many methods to manipulate strings, but some common are:-
Methods | Descriptions | Examples |
len() |
Find the length of the String | s = "Hello"
print(len(s)) # Output: 5 |
lower() |
Converts to lowercase | "Hello".lower() → "hello" |
upper() |
Converts to uppercase | "hello".upper() → "HELLO" |
strip() |
Removes whitespace | " Hello ".strip() → "Hello" |
replace(old, new) |
Replaces substring | "Hello".replace("H", "J") → "Jello" |
split(delim) |
Splits string into list | "Hello World".split() → ["Hello", "World"] |
join(iterable) |
Joins elements of iterable | "-".join(["Hello", "World"]) → "Hello-World" |
find(sub) |
Finds index of substring | "Python".find("th") → 2 |
String Formatting
Python provides multiple ways to format strings:
a) Using format()
b) Using f-strings (In Python 3.6+)
c) Using %
formatting (Old method)
Escape Sequences
- Escape sequences are special characters used in strings to format the strings in the desired way:
Escape Sequence | Description | Example |
\n |
Newline | "Hello\nWorld" |
\t |
Tab space | "Hello\tWorld" |
\' |
Single quote | 'It\'s Python' |
\" |
Double quote | "She said \"Hello\"" |
\\ |
Backslash | "C:\\Users\\Name" |
String Immutability
- Since strings are immutable in Python, i.e. they cannot be changed after creation directly.
But, to modify a string indirectly, we must do it in a new way: –
Looping in a String
- We can iterate through a string using a loop as below:-
0 Comments