Chapter 4 Strings
A string is a sequence of characters, and it is one of the basic data types used to represent text.
Strings are enclosed in either single quotes (') or double quotes ("), and you can use either as long as the opening and closing quotes match. Here are some key characteristics and operations related to strings in Python:
- Creating Strings
# Using single quotes
single_quoted_string = 'Hello, Python!'
# Using double quotes
double_quoted_string = "Hello, Python!"
# Triple-quoted strings for multiline strings
multiline_string = '''This is a
multiline string.'''- String Concatenation
## John Doe
- String Indexing and Slicing
## P
syntax: string_object[from : to : increment]
# Slicing
substring = my_string[1:4:1] # Result: 'yth'
substring = my_string[1:4] # Result: 'yth'
print(substring)## yth
## Pto
4.0.0.1 String Methods:
# Length of a string
length = len(my_string) # Result: 6
# Converting to uppercase and lowercase
uppercase_string = my_string.upper()
lowercase_string = my_string.lower()
# Finding a substring
index_of_th = my_string.find("th") # Result: 2
# Replacing a substring
new_string = my_string.replace("on", "er") # Result: 'Pyther'upper() : strings to uppercase
lower() : strings to lowercase
capitalize() : strings to uppercase 1st letter
## 'OHH! MY LIFE!'
## 'ohh! my life!'
## 'Star'
## True
## True
replace method
replace(): to replace part of a string
syntax: string.replace(oldvalue, newvalue, count)
query = '''
select all_columns
from my_table
'''
new_query = query.replace("my_table", "new_table_name")
print(new_query)##
## select all_columns
## from new_table_name
strip method
strip() method removes leading or trailing white-space
## 'my text'
split method
split() method breaks a string by specified character.
split() method returns list type.
## ['banana', ' apple', ' cherry']
there are some whitespce in the splitted elements in the list
## 'apple'
4.0.0.5 Membership and Operations:
# Checking membership
contains_py = 'py' in my_string # Result: True
# String repetition
repeated_string = my_string * 3 # Result: 'PythonPythonPython'Strings in Python are immutable, meaning once a string is created, you cannot modify its contents. Any operation that appears to modify a string actually creates a new string. Understanding these operations and methods is crucial for working effectively with strings in Python.