Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1. String Functions
- def my_concatenation(str1, str2):
- result = ""
- for char in str1:
- result += char
- for char in str2:
- result += char
- return result
- def my_reverse(string):
- result = ""
- for i in range(len(string) - 1, -1, -1):
- result += string[i]
- return result
- def my_replication(string, n):
- result = ""
- for _ in range(n):
- result = my_concatenation(result, string)
- return result
- def my_slicing(string, start, end):
- result = ""
- for i in range(start, end):
- result += string[i]
- return result
- def my_equals(str1, str2):
- if len(str1) != len(str2):
- return False
- for i in range(len(str1)):
- if str1[i] != str2[i]:
- return False
- return True
- def my_iterate_string(string):
- for char in string:
- print(char, end=" ")
- def my_substring(string, start, length):
- result = ""
- for i in range(start, start + length):
- result += string[i]
- return result
- # Example usage
- string1 = "Hello"
- string2 = "World"
- concatenated_str = my_concatenation(string1, string2)
- reversed_str = my_reverse(string1)
- replicated_str = my_replication(string1, 3)
- sliced_str = my_slicing(string1, 1, 4)
- equal_check = my_equals(string1, string2)
- print("Concatenated String:", concatenated_str)
- print("Reversed String:", reversed_str)
- print("Replicated String:", replicated_str)
- print("Sliced String:", sliced_str)
- print("Equals Check:", equal_check)
- print("\nIterating over the string:")
- my_iterate_string(string1)
- substring_str = my_substring(string1, 1, 3)
- print("\nSubstring:", substring_str)
- --------------------------------------------------------------------------------------------
- 2. Basic Regular Expression
- import re
- print("Matching a pattern")
- pattern = r"apple"
- text = "I like apples and oranges."
- print("Using re.search() to find the first occurrence of the pattern")
- match = re.search(pattern, text)
- if match:
- print(f"Pattern '{pattern}' found at index {match.start()} in the text.")
- else:
- print(f"Pattern '{pattern}' not found in the text.")
- print("\nExtracting matches using groups")
- pattern_with_groups = r"(\w+) (\w+)"
- name_text = "John Doe, Jane Smith"
- print("Using re.findall() to find all occurrences of the pattern with groups")
- matches = re.findall(pattern_with_groups, name_text)
- for match in matches:
- first_name, last_name = match
- print(f"First Name: {first_name}, Last Name: {last_name}")
- print("\nReplacing matches")
- pattern_to_replace = r"apple|orange"
- replacement_text = "fruit"
- print("Using re.sub() to replace all occurrences of the pattern")
- updated_text = re.sub(pattern_to_replace, replacement_text, text)
- print(f"Original Text: {text}")
- print(f"Updated Text: {updated_text}")
- -----
- import re
- # Function to demonstrate basic regular expressions
- def demonstrate_regex(text):
- # 1. Matching a specific pattern
- pattern1 = re.compile(r'apple')
- match1 = pattern1.search(text)
- print("1. Matching 'apple':", match1.group() if match1 else "Not Found")
- # 2. Matching any digit
- pattern2 = re.compile(r'\d')
- match2 = pattern2.search(text)
- print("2. Matching any digit:", match2.group() if match2 else "Not Found")
- # 3. Matching any word character
- pattern3 = re.compile(r'\w+')
- match3 = pattern3.findall(text)
- print("3. Matching any word character:", match3)
- # 4. Matching any non-word character
- pattern4 = re.compile(r'\W+')
- match4 = pattern4.findall(text)
- print("4. Matching any non-word character:", match4)
- # 5. Matching a specific number of occurrences
- pattern5 = re.compile(r'o{2}')
- match5 = pattern5.search(text)
- print("5. Matching 'oo':", match5.group() if match5 else "Not Found")
- # 6. Matching the start of a string
- pattern6 = re.compile(r'^Hello')
- match6 = pattern6.search(text)
- print("6. Matching 'Hello' at the start:", match6.group() if match6 else "Not Found")
- # 7. Matching the end of a string
- pattern7 = re.compile(r'World$')
- match7 = pattern7.search(text)
- print("7. Matching 'World' at the end:", match7.group() if match7 else "Not Found")
- # 8. Matching any character (except for a newline)
- pattern8 = re.compile(r'.')
- match8 = pattern8.findall(text)
- print("8. Matching any character:", match8)
- # Example usage
- sample_text = "Hello apple! 123 World."
- demonstrate_regex(sample_text)
- ----------------------------------------------------------------------------------------------------------------
- doubtful
- 3. Advanced Regular Expressions using Tkinter
- import re
- import tkinter as tk
- from tkinter import ttk
- def validate_input():
- name = name_entry.get()
- email = email_entry.get()
- phone = phone_entry.get()
- # Regular expressions for validation
- name_pattern = re.compile(r'^[A-Za-z\s]+$')
- email_pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
- phone_pattern = re.compile(r'^\d{10}$')
- # Validate name
- if not name_pattern.match(name):
- result_label.config(text="Invalid name format", fg="red")
- return
- # Validate email
- if not email_pattern.match(email):
- result_label.config(text="Invalid email format", fg="red")
- return
- # Validate phone number
- if not phone_pattern.match(phone):
- result_label.config(text="Invalid phone number format", fg="red")
- return
- result_label.config(text="Input is valid", fg="green")
- # Create the main application window
- app = tk.Tk()
- app.title("Data Validation")
- app.geometry("300x200")
- # Create and set up the form
- frame = ttk.Frame(app, padding="10")
- frame.grid(column=0, row=0, sticky=(tk.W, tk.E, tk.N, tk.S))
- name_label = ttk.Label(frame, text="Name:")
- name_label.grid(column=0, row=0, sticky=tk.W, pady=5)
- name_entry = ttk.Entry(frame, width=30)
- name_entry.grid(column=1, row=0, sticky=tk.W, pady=5)
- email_label = ttk.Label(frame, text="Email:")
- email_label.grid(column=0, row=1, sticky=tk.W, pady=5)
- email_entry = ttk.Entry(frame, width=30)
- email_entry.grid(column=1, row=1, sticky=tk.W, pady=5)
- phone_label = ttk.Label(frame, text="Phone:")
- phone_label.grid(column=0, row=2, sticky=tk.W, pady=5)
- phone_entry = ttk.Entry(frame, width=15)
- phone_entry.grid(column=1, row=2, sticky=tk.W, pady=5)
- validate_button = ttk.Button(frame, text="Validate", command=validate_input)
- validate_button.grid(column=0, row=3, columnspan=2, pady=10)
- result_label = ttk.Label(frame, text="")
- result_label.grid(column=0, row=4, columnspan=2)
- # Run the Tkinter event loop
- app.mainloop()
- --------------------------------------------------------------------------------------------------------------
- 4. Calculator using Tkinter
- import tkinter as tk
- from tkinter import ttk
- def on_click(button_text):
- current_text = entry_var.get()
- if button_text == "C":
- entry_var.set("")
- elif button_text == "=":
- try:
- result = eval(current_text)
- entry_var.set(str(result))
- except Exception as e:
- entry_var.set("Error")
- else:
- entry_var.set(current_text + button_text)
- # Create the main application window
- calculator = tk.Tk()
- calculator.title("Calculator")
- # Entry widget for displaying the input and result
- entry_var = tk.StringVar()
- entry = ttk.Entry(calculator, textvariable=entry_var, font=('Arial', 14), justify="right")
- entry.grid(row=0, column=0, columnspan=4, sticky="nsew", pady=10)
- calculator.columnconfigure((0, 1, 2, 3), weight=1)
- # Button layout
- buttons = [
- '7', '8', '9', '/',
- '4', '5', '6', '*',
- '1', '2', '3', '-',
- '0', '.', 'C', '+',
- '='
- ]
- # Add buttons to the grid
- row_val = 1
- col_val = 0
- for button_text in buttons:
- ttk.Button(calculator, text=button_text, command=lambda text=button_text: on_click(text)).grid(row=row_val, column=col_val, sticky="nsew", padx=5, pady=5)
- col_val += 1
- if col_val > 3:
- col_val = 0
- row_val += 1
- # Configure row and column weights
- for i in range(1, 6):
- calculator.rowconfigure(i, weight=1)
- # Run the Tkinter event loop
- calculator.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement