Featured Post

15 Python Tips : How to Write Code Effectively

Image
 Here are some Python tips to keep in mind that will help you write clean, efficient, and bug-free code.     Python Tips for Effective Coding 1. Code Readability and PEP 8  Always aim for clean and readable code by following PEP 8 guidelines.  Use meaningful variable names, avoid excessively long lines (stick to 79 characters), and organize imports properly. 2. Use List Comprehensions List comprehensions are concise and often faster than regular for-loops. Example: squares = [x**2 for x in range(10)] instead of creating an empty list and appending each square value. 3. Take Advantage of Python’s Built-in Libraries  Libraries like itertools, collections, math, and datetime provide powerful functions and data structures that can simplify your code.   For example, collections.Counter can quickly count elements in a list, and itertools.chain can flatten nested lists. 4. Use enumerate Instead of Range     When you need both the index and the value in a loop, enumerate is a more Pyth

Python Split String: Techniques and Best Practices

Here is an example for splitting a string in Python. The functions you need are strip and split to split string, or text. 

python split string


Here's the string taken for split

My task is I want to split address string. Historically, the address is lengthy. It contains the door number, floor number, street number, and street name.

Rama Krishna 20/3 ABC street EFG Nagar US 234567

How to Split a string

The python split string works in two steps. The first step is to use strip function, which removes both leading and trailing spaces. Next, use the the split function, which splits the input string, or text into a list.

Python program

user_address = input("Enter an address")

if user_address.strip(): #check that string is not empty (after removing leading
#and trailing spaces)
    print("Your address is " + user_address)
split_address = user_address.split()
print(split_address)

Output

Interactively, it asks the user to enter the address. After the code runs, the address splits into separate strings in a list.

Enter an address
Rama Krishna 20/3 ABC street EFG Nagar US 234567

Your address is Rama Krishna 20/3 ABC street EFG Nagar US 234567
['Rama', 'Krishna', '20/3', 'ABC', 'street', 'EFG', 'Nagar', 'US', '234567']

** Process exited - Return Code: 0 **
Press Enter to exit terminal

Comments

Popular posts from this blog

How to Fix datetime Import Error in Python Quickly

SQL Query: 3 Methods for Calculating Cumulative SUM

Python placeholder '_' Perfect Way to Use it