Some uses of Python to share _python

Source: Internet
Author: User
1 The use of regular expressions.
Copy Code code as follows:

#正则表达式的模块
Import re
#正则表达式
Repattern = '. *[0-9]{4} '
Pattern = Re.compile (Repattern)
#匹配
If Pattern.match (line):
Return True
Else
Return False

2 Use global variables in the function.
Copy Code code as follows:

def func ():
Global num

3 The Python default print output wraps.
If you need to output without a newline, at the end of the comma can be added.
Copy Code code as follows:

print ' Hello world! ',

4) String segmentation.
Based on a string segmentation, use Split (), the default parameter is white space characters, including spaces, carriage returns, tabs, and so on:
Strlist = Strs.split ('_')
If you need to slice from multiple strings, you can use regular expressions:
Copy Code code as follows:

#根据空格和水平制表符切分
Strlist = Re.split ("[\t\s]", STRs)

5 to determine whether a string is a number.
Copy Code code as follows:

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

6 file reading and writing
Copy Code code as follows:

#读文件
Fin = File (' 1.txt ', ' R ')
#写文件
Fout = File (' 1_ans.txt ', ' W ')
While True:
line = Fin.readline ()
#文件结尾
If Len (line) ==0:
Break
Fout.write (line)
Fin.close ()
Fout.close ()

7) Use of the list
Copy Code code as follows:

Anslist = []
#增加列表里的值
Anslist.append (' Hello1 ')
Anslist.append (' Hello2 ')
#对列表进行排序
Anslist.sort ()
#遍历输出
For ans in anslist
Print ans
Related Article

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.