20 python code snippets that solve everyday problems!

Preface

In this article, I'll share20 Python code snippets to help you with your daily programming challenges. You may already know some of these pieces, but some others may be new to you. Improve your programming skills now with these useful Python code snippets.

1. Simple HTTP Web Server


# 简单的 HTTP 服务器  
import socketserver  
import http.serverPORT = 8000 handler = http.server.SimpleHTTPRequestHandler   
with socketserver.TCPServer(("", PORT), handler) as http:   
    print("Server Launch at Localhost: " + str(PORT))   
    http.serve_forever()#在浏览器中输入http://127.0.0.1:8000/  

2. Single line loop LIST

mylist = [10, 11, 12, 13, 14]  
print([i * 2 for i in mylist]) # [20, 22, 24, 26, 28]  
print([i * 5 for i in mylist]) # [50, 55, 60, 65, 70]  

3. Update dictionary

# 更新字典  
mydict = {1: "Python", 2: "JavaScript", 3: "Csharp"}  
mydict.update({4: "Dart"})  
print(mydict) # {1: 'Python', 2: 'JavaScript', 3: 'Csharp', 4: 'Dart'}  

4. Split multi-line strings

# 拆分多行字符串  
string = "Data \n is encrpted \n by Python"  
print(string)  
# Output  
# Data  
# is encrpted  
# by Python  
splited = string.split("\n")  
print(splited) # ['Data ', ' is encrpted ', ' by Python']  

5. Track the frequency of elements in a list

# Track Frequency  
import collections  
def Track_Frequency(List):  
    return dict(collections.Counter(List))  
print(Track_Frequency([10, 10, 12, 12, 10, 13, 13, 14]))  
# Output  
# {10: 3, 12: 2, 13: 2, 14: 1}  

6. Reading CSV files without using PANDAS

# 简单的类创建  
import csv  
with open("Test.csv", "r") as file:  
    read = csv.reader(f)  
    for r in read:  
        print(row)  
# 输出  
# ['Sr', 'Name', 'Profession']   
# ['1', '小猴子', '数据挖掘工程师']   
# ['2', '云朵君', '算法工程师']  

7. Compress the list into a string

# 压缩字符串列表  
mylist = ["I learn", "Python", "JavaScript", "Dart"]  
string = " ".join(mylist)  
print(string) # I learn Python JavaScript Dart  

8. Get the index of an element in a list


Get the index of an element in a list

mylist = [10, 11, 12, 13, 14] print(mylist.index(10)) # 0 print(mylist.index(12)) # 2 print(mylist.index(14)) # 4

9. The Magic of *ARG

# *arg 的魔法  
def func(*arg):   
    num = 0   
    for x in arg:   
        num = num + x  
print(num) # 600  
func(100, 200, 300)  

10. Get the type of any data

# 获取任意数据的类型  
data1 = 123   
data2 = "Py"   
data3 = 123.443   
data4 = True   
data5 = [1, 2]  
  
print(type(data1)) # <class 'int'>   
print(type(data2)) # <class 'str'>   
print(type(data3)) # <class 'float'>   
print(type(data4)) # <class 'bool'>   
print(type(data5)) # <class 'list'>  

11. Modify the printing function

# 修改打印函数  
print("顶级编程语言是 %r, %r 和 %r" % ('Py', 'Js', 'C#'))  
# 输出  
# 顶级编程语言是“Py”、“Js”和“C#”  

12. Re-capitalize strings

# 字符串的去大写  
data1 = "ABCD"   
data2 = "Py"   
data3 = "Learn Coding"  
print(data1.lower()) # abcd   
print(data2.lower()) # py   
print(data3.lower()) # learn coding  

13. Quick variable exchange method

# 快速交换变量的方法  
d1 = 25   
d2 = 50  
d1, d2 = d2, d1  
print(d1, d2) # 50 25  

14. Print with delimiters

# 带分隔符打印  
print("Py", "Js", "C#", sep="-") # Py-Js-C#  
print("100", "200", "300", sep="x") # 100x200x300  

15. Get web page HTML data

# 使用 pip 安装请求的第一个安装请求导入请求  
r = requests.get("https://www.baidu.com/s?wd=数据STUDIO ")   
print(r) # 显示整页html数据  

16. Obtaining data takes up memory

# 获取数据占用的内存导入系统  
import sys  
def memory(data):  
    return sys.getsizeof(data)  
print(memory(100)) # 28  
print(memory("Pythonnnnnnn")) # 61  

17. Simple class creation

# 简单的类  
class Employee:  
    def __init__(self, empID):  
        self.empID = empID  
        self.name = "Haider"  
        self.salary = 50000  
      
    def getEmpData(self):  
        return self.name, self.salary  
emp = Employee(189345)  
print(emp.getEmpData()) # ('Haider', 50000)  

18. String multiplier

# 字符串乘数#   
# 正常方式   
for x in range(5):  
    print("C#")  
      
# 更好的方式  
print("C# "*5) # C# C# C# C# C#  

19.Chain comparison

# 链式比较  
a = 5   
print(1 == a < 2) # False  
print(2 < 3 < 6 > a) # True  

20. Numerical integer values

# 数字化  
integer = 234553  
digitz = [int(i) for i in str(integer)]  
print(digitz) # [2, 3, 4, 5, 5, 3]  

The recent popular artificial intelligence applications such as ChatGPT have had a positive impact on the Python programming language. It has promoted the popularity and development of Python, enhanced the status of Python in the fields of text processing and NLP, and promoted the growth of the Python ecosystem.

Learning Python well is good whether you are getting a job or doing a side job to make money, but you still need to have a learning plan to learn Python. Finally, we share a complete set of Python learning materials to give some help to those who want to learn Python!

-END-


I have also compiled some introductory and advanced information on Python for you. If you need it, you can refer to the following information.

About Python technical reserves

Learning Python well is good whether you are getting a job or doing a side job to make money, but you still need to have a learning plan to learn Python. Finally, we share a complete set of Python learning materials to give some help to those who want to learn Python!

1. Python learning route

Insert image description here

Insert image description here

2. Basic learning of Python

1. Development tools

We will prepare you with the essential tools you need to use in the Python development process, including the latest version of PyCharm to install permanent activation tools.
Insert image description here

2. Study notes

Insert image description here

3. Learning videos

Insert image description here

3. Essential manual for Python beginners

Insert image description here

4. Python practical cases

Insert image description here

5. Python crawler tips

picture

6. A complete set of resources for data analysis

Insert image description here

7. Python interview highlights

Insert image description here

Insert image description here

2. Resume template

Insert image description here
Insert image description here

Data collection

The complete set of Python learning materials mentioned above has been uploaded to CSDN official. If you need it, you can scan the CSDN official certification QR code below on WeChat and enter "receive materials" to get it.

Insert image description here

Guess you like

Origin blog.csdn.net/xiqng17111342931/article/details/134363449