5 Tips to Refine Code | Web Scraping Tool | ScrapeStorm
Abstract:This article will introduce 5 tips to refine codes. ScrapeStormFree Download
The level of code can be seen at a glance from the form of writing the code. It takes experience to write code that is easy to read, sophisticated and efficient. In this article, I’ll give you tips for refining the five codes.
1. Ternary Expression
Usually, the conditional expression is written as follows:
condition = True
if condition:
x = 1
else:
x = 0
print(x)
See below for more readability and less code:
condition = True
x = 1 if condition else 0
print(x)
2. Separate numbers with underscores
num1 = 100000000
num2 = 10000000
total = num1 + num2
print(total)
You can write like this.
num1 = 10_000_0000
num2 = 10_000_000
total = num1 + num2
print(total)
If you want to use commas to separate the outputs, you can also do the following:
num1 = 10_000_0000
num2 = 10_000_000
total = num1 + num2
print(f”{total:,}”)
This makes the numbers easier to read.
3. use ” With “
The usual steps to open a file are:
f = open(“text.txt”,”r”)
file_contents = f.read()
f.close()
words = file_contents.split(” “)
word_count = len(words)
print(word_count)
It is recommended to use “With” so that Python will handle the closing of the file automatically.
with open(“text.txt”,”r”) as f:
file_contents = f.read()
words = file_contents.split(” “)
word_count = len(words)
print(word_count)
4. use “enumerate”
names = [‘dvid’,’xiaoming’,’lilei’,’hanmeimei’]
index = 0
for name in names:
print(index,name)
index += 1
To get the index of the list, look like this:
names = [‘dvid’,’xiaoming’,’lilei’,’hanmeimei’]
for index,name in enumerate(names):
print(index,name)
5. use “getpass” when entering the password
When entering the password, use “getpass” to protect the password without echoing the characters typed.
>>>password = input(“Enter password:”)
Enter password: mypassword
>>> password
‘mypassword’
>>> from getpass import getpass
>>> password2 = getpass(“Enter password:”)
Enter password:
>>> password2
‘123456’
>>>
Disclaimer: This article is contributed by our user. Please advise to remove immediately if any infringement caused.