In this study note, we’ll delve into fundamental Python concepts and syntax, including parsing strings, handling escape sequences, and string formatting. Additionally, we’ll explore examples of using nested loops in Python.
Parsing Strings:
Parsing strings involves extracting specific information or manipulating strings in Python.
Data = ‘some string with email@something.something at Wednesday, 09:08:15’
Index = Data.find(‘@’)
print(Index)
SpaceFinding = Data.find(‘ ‘, Index) # find space after @
print(SpaceFinding)
Domain = Data[Index+1: SpaceFinding] # it counts after @ until the first space
print(Domain) # prints something.something
String = “Let’s split this phrase”
Output = String.split()
print(Output) # It prints a list of the words
Output = String.split(“_”, maxsplit=1) # split one time by _
JoinString = “_”.join(Output)
print(JoinString) # this joins back strings by _ for example let’s_split_this_phrase
Escape Sequences:
Escape sequences are used to represent characters that are difficult or impossible to type directly. Here’s how you can handle escape sequences in Python:
Discord = ”’ He said “I am gonna block you”. ”’
print(Discord)
# Escaping single quotes
print(‘He said “Why do you always wanna try something I got, for Jesus\’ sake ” ‘)
# Escaping double quotes
print(“He said \”I am gonna block you\””)
# Handling slashes
print(“C:\\mycomputer\\file”) # Put two \\ next to \ to ignore \
print(r”C:\mycomputer\file”) # r in front of string can escape backslashes
String Formatting:
String formatting allows you to create dynamic strings by incorporating variables and values into a formatted string. Here are several methods of string formatting in Python:
ErrorNumber = 1232532
Name = “Daniel”
# Using % operator
print(‘Hi, %s’ % Name)
print(‘%x’ % ErrorNumber)
print(‘Hi, %s, there is a 0x%x error!’ % (Name, ErrorNumber))
# Using str.format
print(‘Hi, {}’.format(Name))
print(‘Hi {}, there is a 0x{:x} error!’.format(Name, ErrorNumber))
# Using f-strings (formatted string literals)
print(f’Hi {Name}, there is a {ErrorNumber:#x} error!’)
Example: Creating a Pattern using Nested Loops
Let’s create a pattern using nested loops in Python:
def pattern(n):
for i in range(0, n):
for j in range(0, i+1):
print(“*”, end=’ ‘)
print()
for i in range(n, 0, -1):
for j in range(0, i-1):
print(“*”, end=’ ‘)
print()
For example, if `n = 3`, the pattern will be:
“`
*
**
***
**
*
“`
These study notes cover essential Python concepts, including string parsing, escape sequences, string formatting, and nested loops. Practice these concepts to strengthen your Python programming skills.