In Python, a string is a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “). Strings are used to represent text in Python, and they are immutable, meaning once created, they cannot be changed.
Note:-
Strings are used to record textual information as well as arbitrary collections of bytes
strings are sequences of one-character strings
Creating a String
You can create a string by assigning a sequence of characters to a variable.
# Single quotes
name = 'John'
# Double quotes
greeting = "Hello, world!"
Multiline Strings
To create a multiline string, you can use triple quotes (‘ ‘ ‘or”””):
multiline_string = '''This is
a multiline
string.'''
String Indexing and Slicing
Indexing allows you to access individual characters in a string, using a zero-based index. Negative indexing starts from the end.
Slicing allows you to extract a part of the string by specifying a range.
text = "Python"
print(text[0]) # Output: 'P' (first character)
print(text[-1]) # Output: 'n' (last character)
print(text[1:4]) # Output: 'yth' (characters from index 1 to 3)
Common String Methods
Python provides several built-in methods to manipulate and work with strings. Here are some common methods:
lower(): Converts the string to lowercase.
upper(): Converts the string to uppercase.
strip(): Removes leading and trailing spaces.
replace(old, new): Replaces occurrences of a substring.
split(delimiter): Splits the string into a list of substrings.
join(iterable): Joins elements of an iterable (like a list) into a single string.
text = " Hello, Python! "
print(text.lower()) # Output: " hello, python! "
print(text.upper()) # Output: " HELLO, PYTHON! "
print(text.strip()) # Output: "Hello, Python!"
print(text.replace("Python", "World")) # Output: " Hello, World! "
String Concatenation
You can concatenate strings using the +
operator or join multiple strings with spaces using join().
first_name = "John"
last_name = "Taylor"
full_name = first_name + " " + last_name # Concatenation
print(full_name) # Output: "John Taylor"
String Formatting
You can insert variables into strings using several methods:
1. F-strings (Python 3.6+):
name = "John"
age = 35
print(f"My name is {name} and I am {age} years old.")
2. format() method:
print("My name is {} and I am {} years old.".format(name, age))
3. Percent (%) formatting:
print("My name is %s and I am %d years old." % (name, age))