This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

New blog post again!! Here are some of the most common python syntax tips that you might not know about: If you find it useful, don’t forget to like it. Ok, let’s start.


Do you know what a**3 means?


Do you know how to print module paths?


Do you know how to use the reduce () function and how to concatenate strings with lists?


Yet you probably know all about it

But read on, there may be some Python hacks you didn’t know could more than double your productivity!!

If judgment

Can be used directly to determine whether a variable is in the list

We can verify multiple values using the following method:


if 7 in [1.3.5.7.9] :print(Learn "fat"(答案 : it is no longer necessary to use:if m==1 or m==3 or m==5 or m==7:
Copy the code

Four ways to flip a string/list

TestList = [1.3.5]
testList.reverse()
print(testList)
# - > [5, 3, 1)
Copy the code
Flip in a loop and iterate over the outputfor element in reversed([1.3.5) :print(element)


# 1 - > 5

# 2 - > 3

# 3 - > 1
Copy the code
A line of code flips the string"Test Python"[: : -1]

# output "nohtyP tseT"More examples:>>> a=[1.2.3.4.5.6.7]
>>> b=(1.2.3.4.5.6.7)
>>> c='Let me show you a little thing'
>>> a[::-1]
[7.6.5.4.3.2.1]
>>> b[::-1]
(7.6.5.4.3.2.1)
>>> c[::-1]
'gniht elttil a uoy wohs em teL'
>>> a
[1.2.3.4.5.6.7]
>>> b
(1.2.3.4.5.6.7)
>>> c
'Let me show you a little thing'

>>> a.reverse()
>>> a
[7.6.5.4.3.2.1Compared with reverse, the slicing method does not change the structure of the list, so it is a more useful technique in practical applicationCopy the code
Using slice flip list [1.3.5] [: : -1]

# output,3,1 [5]
Copy the code

Square number

a=5
a**2=25
a**3=125

Copy the code

Hexadecimal conversion

dec = input('Base 10 is:')
print("Convert to binary as:".bin(dec))
print("Convert to octal as:".oct(dec))
print("Convert to hexadecimal:".hex(dec))
 
string1 = '101010'
print('Binary string converted to decimal number:'.int(string1,2))
string1 = '367'
print('Octal string converted to decimal number:'.int(string1,8))
string3 = 'FFF'
print('Convert a hexadecimal string to a decimal number as:'.int(string1,16))

Copy the code

Converts lowercase letters in a string to uppercase letters

str = "this is string example from runoob.... wow!!!";

print ("str.upper() : ".str.upper()) The output of the above example is as follows:str.upper() : THIS IS STRING EXAMPLE FROM RUNOOB.... WOW!!!Copy the code

Initialize multiple variables at once


a,b,c,d=1.2.3.4You can use listsList = [1.2.3]
x,y,z=List
print(x, y, z)
# - > 1, 2, 3
Copy the code

Print module path


import socket
print(socket)
# < module 'socket' from '/ usr/lib/python2.7 / socket. Py' >
Copy the code

List to heavy

list0 = [1.2.3.2.2.5.6.5]
list0 = list(set(list0))
>>> list0
[1.2.3.5.6]
Copy the code

Dictionary and list derivation


# list
l=[[0 for i in range(4)] for i in range(4)]# Generate a 2d list
print(l)
# [[0, 0, 0, 0] to [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Copy the code
# Dictionary derivation
testDict = {i: i * i for i in xrange(10)}
testSet = {i * 2 for i in xrange(10)}

print(testSet)
print(testDict)

#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
# {0:0, 1, 1, 2, 4, 3, 9, 4:16, 5:25, 6:36, 7:49, 8, 64, 9:81}
Copy the code

Concatenated string

You may have seen this splice a="i "
b="love "
c="you"
print(a+b+c)
Copy the code
Look at this l=['a'.'b'.'c']
print(' 'join(l))
# is separated by the character to the left of the join
Copy the code

Cyclic enumeration index

It's easy to find the subscripts and the corresponding elementslist = [10.20.30]
for i, value in enumerate(list) :print(i, ':', value)

# 1 - > 0:10
# 2 - > 1:20
# 3 - > 2:30
Copy the code

Enabling File Sharing

Python allows you to run an HTTP server to share files from the root path, and the command will be on the default port, i.e8000To start a server, you can pass a custom port number as the last parameter to the above command. Here is the command python3 -m http.server to start the serverCopy the code

Use the else statement (important)

pythonelseClause can not only be used inifStatement, but also infor,while 和 tryThis is not a secret language feature, but it is not taken seriously. l=[1.2.3.4.5]
for i in l:
    if i=='6':
        print(Awesome!)
        break
else:
    print(999)
Copy the code

split

Python split() slices the string by specifying a delimiter, and if the num argument has a value, only the num substring is separated. Grammar:str.split(str="", num=string.count(strSimplified:))str.split("")
Copy the code

reduce

Reduce applies a function to a sequence [x1, x2, x3,... On, this function must take two arguments, reduce will continue the result and the next element of the sequence to do the cumulative calculation.>>> from functools import reduce
>>> def fn(x, y) :
        return x * 10 + y

>>> reduce(fn, [1.3.5.7.9])
13579
Copy the code

Let’s combine our recent knowledge and do a problem

Enter aintReturns a new integer without repeating numbers in the order read from right to left. result=""
for i in input[: : - ()1] :if i not in result:
        result+=i
print(result)
Copy the code

sorted


>>> sorted([36.5, -12.9, -21[-])21, -12.5.9.36]
# You can receive a key function to implement a custom sort, such as sorting by absolute value:
>>> sorted([36.5, -12.9, -21], key=abs)
[5.9, -12, -21.36] Let's look at another example of string sorting:>>> sorted(['bob'.'about'.'Zoo'.'Credit'[])'Credit'.'Zoo'.'about'.'bob'We givesortedPass the key function to enable case-insensitive sorting:>>> sorted(['bob'.'about'.'Zoo'.'Credit'], key=str.lower)
['about'.'bob'.'Credit'.'Zoo'] to reverse the order, you can pass a third argument, reverse=, without changing the key functionTrue:>>> sorted(['bob'.'about'.'Zoo'.'Credit'], key=str.lower, reverse=True)
['Zoo'.'Credit'.'bob'.'about']
Copy the code

Executes a string expression and returns the value of the expression

>>>x = 7
>>> eval( '3 * x' )
21
>>> eval((2, 2 'pow)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
Copy the code