“Python is a truly beautiful language. When someone comes up with a good idea, it takes about a minute and five lines of code to write something that almost meets your requirements. Then it only takes an hour to scale the script up to 300 lines, and it’s still pretty much what you need.” -Jack Jansen

Click here and the code will run

1. Print the string N times

You might use a loop to print the string N times. But I’ll show you a nice way to print a string N times in a small line of code.

string = "Python "
ntimes = string * 3
print(ntimes) # Python Python Python
Copy the code

2. The function returns multiple values

Sometimes functions need to return multiple values. We can do this as follows:

def MultiReturn() :
    return 1.2.3
a, b, c = MultiReturn()
print(a,b,c) # 1, 2, 3
Copy the code

3. Import the module file path

Did you know that we can get the file path of any imported module in Python? This is a great feature when you need to know the path to a module. See the following code example:

import os
import json

print(os) # <module 'os' from '/usr/lib/python3.6/os.py'>
print(json) # < module 'json' from '/ usr/lib/python3.6 / json/set p y' >
Copy the code

4. Quickly invert strings

To understand the following code, you may need to delve into Python slicing operations.

string = "Python"
print(string[::-1]) # nohtyP
Copy the code

Grammar: string [start: end: stop]

  • start: Start position, default is 0
  • end: End position. The default value is a string length
  • stopThe: parameter can be omitted. The default value is 1. It can be negative to indicate reverse order.

5. Multivariable assignment

Many other languages C++, Java, and JavaScript allow only one assignment to a variable. But Python allows you to perform multiple assignments, which can be useful in different situations.

a, b = 1.2
print(a,b) # 1 2
Copy the code

6. Go to heavy

In Python, you no longer need to loop to remove duplicates from lists; you can use built-in functions to do this quickly and easily. Look at the code below.

lst1 = [1.3.3.4.5.1]
lst2 = ["A"."A"."B"."C"."D"."D"]
print(set(lst1)) # {1, 3, 4, 5}
print(set(lst2)) # {'A', 'B', 'C', 'D'}
Copy the code

7. Format the string

You usually use the + unary operator to format strings. In short, when you want to append a variable to a string, you can use the unary operator +. But I’ll show you how to do this formatting in a quick and easy way.

name = "John"
age = 23
# method 1
print("My name is " + name + " and I am " + str(age)) # My name is John and I am 23
# method 2
print("My name is {0} and I am {1}".format(name, age)) # My name is John and I am 23
# method 3
print(f"My name is {name} and I am {age}") # My name is John and I am 23
Copy the code

8. Initialize variables

You can initialize empty containers in Python. In short, you can declare data structures without assigning values or populating them.

lst = [] Initialize an empty list
dct = {} Initialize an empty dictionary
tpl = () Initialize an empty tuple
set = set(a)Initialize an empty collection
Copy the code

9. Do your Python objects take up memory?

Did you know that Python’s built-in module SYS can tell you how much memory an object consumes in Python?

import sys
print(sys.getsizeof(1)) # 28
print(sys.getsizeof(1.0)) # 24
print(sys.getsizeof(True)) # 1
print(sys.getsizeof(None)) # 1
print(sys.getsizeof("Hello")) # 56
print(sys.getsizeof([])) # 40
print(sys.getsizeof(())) # 40
print(sys.getsizeof({})) # 40
print(sys.getsizeof(set())) # 40
Copy the code

Reverse the list

Refer to # 4 of this article to reverse strings.

lst = [1.3.3.4.5.1]
print(lst[::-1]) # [1, 5, 4, 3, 3, 1]
Copy the code

11. Reverse the dictionary

I’ll share a sample code to reverse dictionaries. In short, keys and values will swap their positions.

dict = {'x' : 1.'y' : 2.'z' : 3}
new_dict = { value : key  for key , value in dict.items()}
print(new_dict) # {1: 'x', 2: 'y', 3: 'z'}

## Try the following code and be surprised
dict = {'x' : 1.'y' : 2.'z' : 2}
new_dict = { value : key  for key , value in dict.items()}
print(new_dict) # {1: 'x', 2: 'z'}
Copy the code

12. More advanced multivariable assignment

Earlier in this article, we learned how to do multivariable replication. In this tip, we will learn advanced methods of multivariable replication.

a, *b, c, d = 3.4.5.6.7
print(a) # 3
print(b) # [4, 5]
print(c) # 6
print(d) # 7

## ⚠️ Try the following code
a, *b, c= 3.4.5.6.7
print(a) # 3
print(b) # [4, 5, 6]
print(c) # 7

Copy the code

13. String in connection list

You might use a loop to iterate through a list and concatenate each item in the list. But it takes a lot of lines of code to do that. The join() method can be used to do this quickly and easily.

lst = ['a'.'b'.'c']
print(' '.join(lst)) # abc
Copy the code

14. Merge dictionaries

dict1 = {'a' : 1.'b' : 2}
dict2 = {'c' : 3.'d' : 4}
dict3 = {**dict1, **dict2}
print(dict3) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Copy the code

15. Is there a limit to how many times Python recurses?

Python actually sets the recursive limit to 1000 by default when using recursive functions, but the limit can be changed by using the following code:

import sys
current_recursion_limit = sys.getrecursionlimit()
print(current_recursion_limit) # 1000
set_limit = sys.setrecursionlimit(2000)
print(set_limit) # 2000
Copy the code

16. How to pick out files with the suffix XLS or XLSX?

You’ve probably used the startWith and endWith methods to search for prefixes or suffixes in strings. But you don’t necessarily know that they can use multiple conditions.

string1 = 'abc.xls'
# method 1
if string1.endswith('.xls') or string1.endswith('.xlsx') :print('Yes')
# method 2
if string1.endswith(('.xls'.'.xlsx')) :print('Yes')
Copy the code

17. Learn to substitute in for multiple if statements

a = [1.2.3]
x = 1
# method 1
if a[0] == x or a[1] == x or a[2] == x:
    print('Number X is present in the list')

# method 2
if x in a:
    print('Number X is present in the list')
Copy the code

section

The 17 python tips shared above will help you!

Welcome everyone to like, favorites, support!

Pythontip, Happy Coding!

Public number: quark programming