- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
String Introduction:
A string is a sequence of characters. In Python, you can define a string using either single quotes (‘) or double quotes (“), or triple quotes (”’ or “””) for multiline strings. Here are some examples:
# Defining strings in Python
# Single-quoted string
single_quote_str = 'Hello, World!'
print("Single-quoted string:", single_quote_str)
# Double-quoted string
double_quote_str = "Hello, Python!"
print("Double-quoted string:", double_quote_str)
# Triple-quoted string (for multiline text)
triple_quote_str = '''This is a
multiline string.
It spans multiple lines.'''
print("Triple-quoted string:")
print(triple_quote_str)
Re-assign Strings:
In Python, you can reassign a string to a new value by simply assigning the new value to the variable that holds the string. Here’s an example:
# Initial string assignment
my_string = "Hello, World!"
print("Original string:", my_string)
# Reassigning the string to a new value
my_string = "Welcome to Python!"
print("Reassigned string:", my_string)
In the example above, the first print statement outputs “Hello, World!” because my_string is initially assigned that value. Then, my_string is reassigned to “Sqatools” and the second print statement outputs the new value.
# Example to demonstrate string immutability in Python
# 1). String Concatenation
greeting = "Hello"
new_greeting = greeting + ", World!"
print("Original string (after concatenation):", greeting) # Output: Hello
print("New string (concatenation result):", new_greeting) # Output: Hello, World!
# 2). String Replacement
my_string = "Hello, Python!"
new_string = my_string.replace("Python", "World")
print("\nOriginal string (after replacement):", my_string) # Output: Hello, Python!
print("New string (replacement result):", new_string) # Output: Hello, World!
# 3). String Slicing
text = "Immutable"
sliced_text = text[:3] # Taking the first three characters
print("\nOriginal string (after slicing):", text) # Output: Immutable
print("Sliced string (slicing result):", sliced_text) # Output: Imm
Deleting string:
In Python, you cannot delete individual characters in a string because strings are immutable. However, you can delete the entire string object from memory using the del statement. Here’s an example:
# Define a string
my_string = "Hello, World!"
print(my_string) # Outputs: Hello, World!
# Delete the string object
del my_string
# Try to access the deleted string
try:
print(my_string)
except NameError as e:
print(e) # Outputs: name 'my_string' is not defined
In the example above, the first print statement outputs the value of my_string, which is “Hello, World!”. Then, the del statement deletes the my_string object from memory. When we try to print my_string again, we get a NameError because the variable no longer exists.
String formatting methods:
Python provides several methods for formatting strings. Here are the most commonly used methods:
- The % operator: This operator allows you to format strings using placeholders, which are replaced with values at runtime. Here’s an example:
# Using the % operator for string formatting
name = "Alice"
age = 25
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.
In the example above, %s and %d are placeholders for the name and age variables, respectively. The values of these variables are provided in a tuple that follows the % operator.
- The str.format() method: This method allows you to format strings using placeholders that are enclosed in curly braces. Here’s an example:
# Using the str.format() method for string formatting
name = "Alice"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.
In the example above, {} is a placeholder for the name and age variables. The values of these variables are provided as arguments to the str.format() method.
- F-strings: It allows you to embed expressions inside placeholders that are enclosed in curly braces preceded by the f character. Here’s an example:
# Using f-strings for string formatting
name = "Alice"
age = 25
# Embedding variables directly into the string
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Output: My name is Alice and I am 25 years old.
In the example above, the f character before the string indicates that it is an f-string. The expressions inside the curly braces are evaluated at runtime and the resulting values are inserted into the string.
String operators:
In Python, strings support several operators that can be used to perform various operations on strings. Here are some of the most commonly used string operators:
- Concatenation (+): The + operator can be used to concatenate two or more strings. Here’s an example:
# Using the + operator to concatenate strings
str1 = "Hello"
str2 = "World"
combined_str = str1 + " " + str2 # Adding a space between the words
print(combined_str)
# Output: Hello World
- Repetition (*): The * operator can be used to repeat a string a certain number of times. Here’s an example:
# Using the * operator to repeat a string
str1 = "Hello "
repeated_str = str1 * 3 # Repeating the string 3 times
print(repeated_str)
# Output: Hello HelloHello
- Membership (in): The in operator can be used to check if a substring exists within a string. It returns True if the substring is found, and False otherwise. Here’s an example:
# Using the 'in' operator to check membership
sentence = "Python is awesome!"
# Checking if a substring exists within the string
substring = "Python"
result = substring in sentence
print(result)
# Output: True
- Indexing ([]): The [] operator can be used to access individual characters within a string. You can use a positive index to access characters from the beginning of the string, and a negative index to access characters from the end of the string. Here’s an example:
# Using the [] operator for indexing a string
my_string = "Python"
# Accessing characters using positive indices
first_char = my_string[0] # First character
last_char = my_string[5] # Last character (index 5 for "n")
print("First character:", first_char) # Output: P
print("Last character:", last_char) # Output: n
# Accessing characters using negative indices
second_last_char = my_string[-2] # Second last character (index -2 for "o")
print("Second last character:", second_last_char) # Output: o
- Slicing ([start:end]): The [] operator can also be used to extract a substring (or slice) from a string. The start argument specifies the starting index of the slice (inclusive), and the end argument specifies the ending index of the slice (exclusive). Here’s an example:
# Using the [] operator for string slicing
my_string = "Python Programming"
# Extracting a substring using slicing
substring = my_string[0:6] # From index 0 to 5 (6 is exclusive)
print(substring) # Output: Python
- Comparison (==, !=, <, <=, >, >=): The comparison operators can be used to compare two strings alphabetically.
# Comparison of strings using various operators
string1 = "Apple"
string2 = "Banana"
# Checking if the strings are equal
print(string1 == string2) # Output: False
# Checking if the strings are not equal
print(string1 != string2) # Output: True
# Checking if string1 is alphabetically less than string2
print(string1 < string2) # Output: True
# Checking if string1 is alphabetically greater than string2
print(string1 > string2) # Output: False
# Checking if string1 is alphabetically less than or equal to string2
print(string1 <= string2) # Output: True
# Checking if string1 is alphabetically greater than or equal to string2
print(string1 >= string2) # Output: False
String indexing and slicing:
Indexing:
Indexing: Each character in a string is assigned an index starting from 0. You can access a particular character in a string using its index. Here’s an example:
# Using indexing to access characters in a string
my_string = "Python"
# Accessing individual characters using their indices
first_char = my_string[0] # First character
second_char = my_string[1] # Second character
last_char = my_string[5] # Last character
print("First character:", first_char) # Output: P
print("Second character:", second_char) # Output: y
print("Last character:", last_char) # Output: n
Slicing:
You can extract a portion of a string using slicing. Slicing is done using the [] operator, with two indices separated by a colon (:) inside the brackets. Here’s an example:
# Using slicing to extract a portion of a string
my_string = "Python Programming"
# Slicing from index 0 to 6 (exclusive of index 6)
substring = my_string[0:6] # This gives 'Python'
print(substring) # Output: Python
In the example above, my_string[0:5] returns the first five characters of the string, my_string[:5] returns all the characters up to the fifth character, and my_string[-5:] returns the characters from the fifth-last to the last character.
Note that the first index in a slice is inclusive and the second index is exclusive. So, my_string[0:5] returns characters from index 0 to index 4, but not the character at index 5.
In addition to the two indices separated by a colon, you can also add a third index to specify the step value. Here’s an example:
# Using slicing with a step
my_string = "Python Programming"
# Extracting every second character from index 0 to index 12
substring = my_string[0:13:2] # From index 0 to 12, taking every second character
print(substring) # Output: Pto rg