Python usage-Python tutorial

Source: Internet
Author: User
I learned some python recently. I had to process a file yesterday, so I tried it. 1) use of regular expressions.

The code is as follows:


# Regular expression module
Import re
# Regular expression
RePattern = '. * [0-9] {4 }'
Pattern = re. compile (rePattern)
# Matching
If pattern. match (line ):
Return True
Else:
Return False


2) use global variables in functions.

The code is as follows:


Def func ():
Global num


3) by default, python outputs a line feed in print.
If you do not need to output a line break, add a comma at the end.

The code is as follows:


Print 'Hello World! ',


4) string splitting.
Use split () to split a string. the default parameter is blank, including spaces, carriage returns, and tabs:
StrList = strs. split ('_')
To split strings, use the regular expression:

The code is as follows:


# Split based on spaces and horizontal tabs
StrList = re. split ("[\ t \ s]", strs)


5) determine whether a string is a number.

The code is as follows:


If str. isdigit ():
Return True
Else:
Return False


6) file read/write

The code is as follows:


# Reading files
Fin = file('1.txt ', 'r ')
# Writing files
Fout = file('audio ans.txt ', 'w ')
While True:
Line = fin. readline ()
# End of a file
If len (line) = 0:
Break
Fout. write (line)
Fin. close ()
Fout. close ()


7) Use of the list

The code is as follows:


AnsList = []
# Adding values in the list
AnsList. append ('hello1 ')
AnsList. append ('hello2 ')
# Sort the list
AnsList. sort ()
# Traverse output
For ans in ansList
Print ans

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.