Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Common Python Operations: Files, Lists, and Strings

Tech 1

File Handling in Python

1. Opening a file

To open a file, use Python's built-in open() function, which accepts the file path and access mode as parameters.

sample_file = open("sample.txt", "r") # Opens sample.txt in read-only mode

2. Reading file content

Use the read() method to load the full content of an open file.

full_content = sample_file.read() # Reads entire file content into the full_content variable

3. Writing to a file

Use the write() method to add content to an open file (requires write-enabled access mode).

sample_file.write("Hello, Python World!") # Writes the target string to the open file

4. Closing a file

After completing operations, always close the file to release system resources with the close() method.

sample_file.close() # Closes the previously opened file

5. Error Handling

File operations can encounter errors such as missing files or insufficient permissions. Use Python's exception handling mechanism to manage these errrors gracefully.

try:
    with open("missing_file.txt", "r") as f:
        content = f.read()
except Exception:
    print("An error occurred during file operation")

6. Context Manager

Use Python's context manager (via the with statement) to automatically handle opening and closing files, avoiding manual resource management errors.

with open("temp_data.txt", "r") as data_file:
    file_contents = data_file.read()

List Operations in Python

1. Creating a List

Use square brackets [] to create an empty list, or add comma-separated elements inside brackets to create a populated list.

empty_list = [] # Creates an empty list
number_list = [5, 10, 15] # Creates a list with three elements

2. Accessing List Elements

Use zero-based indexing to access specific elements in a list.

number_list = [5, 10, 15]
print(number_list[0]) # Outputs the first element: 5

3. Get List Length

Use the built-in len() function to get the number of elements in a list.

number_list = [5, 10, 15]
list_length = len(number_list) # Returns a length value of 3

4. List Slicing

Use slicing to extract a sublist from an existing list. The syntax uses a colon inside square brackets to specify the start (inclusive) and end (exclusive) indices.

full_list = [2, 4, 6, 8, 10]
print(full_list[1:3]) # Outputs the new sublist [4, 6]

5. Add Elements to a List

Use the append() method to add a new element to the end of a list.

item_list = [1, 3, 5]
item_list.append(7) # Adds 7 to the end of the list

6. Remove Elemants from a List

Use the remove() method to delete the first occurrence of a specified value from a list.

value_list = [10, 20, 30]
value_list.remove(20) # Removes the value 20 from the list

7. Sort a List

Use the sort() method to sort a list in-place in ascending order by default.

unsorted_list = [9, 2, 6, 1]
unsorted_list.sort() # Sorts the list to become [1, 2, 6, 9]

8. Reverse a List

Use the reverse() method to reverse the order of all elements in a list in-place.

original_list = [1, 2, 3]
original_list.reverse() # Results in the reversed list [3, 2, 1]

String Manipulation in Python

1. String Concatenation

Use the + operator to join two or more strings into a single string.

greeting = "Hello"
topic = "Python"
full_text = greeting + ", " + topic

2. String Formatting

String formatting inserts dynamic variable values into a static string template. You can use % formatting or the format() method for this.

username = "Bob"
welcome_msg = "Hi there, %s!" % username # Results in the string "Hi there, Bob!"

3. String Indexing and Slicing

Strings in Python are sequence types that support zero-based indexing for accessing individual characters, and slicing for extracting substrings.

sample_text = "Python"
print(sample_text[0]) # Outputs the first character: "P"

To extract a substring:

sample_text = "Python"
print(sample_text[1:4]) # Outputs the substring "yth"

4. Get String Length

Use the built-in len() function to get the number of characters in a string.

input_str = "Programming"
str_length = len(input_str) # Returns a length of 11

5. Find and Replace Substrings

The find() method returns the starting index of the first matching substring, or -1 if no match is found.

main_str = "Welcome to Python"
match_index = main_str.find("Python") # Returns starting index 11

The replace() method creates a new string with all occurrences of a target substring replaced by a new value:

original_str = "Welcome to Python"
updated_str = original_str.replace("Python", "Programming") # Results in "Welcome to Programming"

6. Split and Join Strings

The split() method splits a string into a list of substrings, using whitespace as the default delimiter.

sentence = "Python is fun"
word_list = sentence.split() # Results in the list ["Python", "is", "fun"]

The join() method combines a list of strings into a single string, with a specified separator between elements:

phrases = ["Learning", "Python", "is", "great"]
combined = " ".join(phrases) # Results in the string "Learning Python is great"
Tags: Python

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.