您的位置:首页 > 编程语言 > Python开发

Python 基础语法知识

2012-07-16 11:25 686 查看
原文地址:http://www.linuxidc.com/Linux/2011-04/34055.htm

Python 随版本的不同,语法也有一些差异。 具体可以参考最新的Python帮助文档。 以下说明都是基于Python 3.1 版本。

一. Python 变量类型
#整型
integer_number = 90

#浮点
float_number = 90.4

#复数
complex_number = 10 + 10j

#list 序列:列表、元组和字符串都是序列,序列的两个主要特点是索引操作符和切片操作符。

sample_list = [1,2,3,'abc']

#dictionary 字典
sample_dic = {"key":value, 2:3}

#tuple 只读的序列
sample_tuple = (1,3,"ab")

二. Python 程序流程控制
2.1 条件判断结构
flag1 = some_value
flag2 = other_value
if flag1:
do_function_1()
elif flag2:
do_function_2()
else:
do_function_3()

2.2 循环结构
for i in range(0, 10):
print(i)

for i in ['a','b','c','dd','eee'];
print(i)

三. Print 函数及格式化输出
3.1 Print 自动换行
在Python 3.0 以后,Python 在print 函数上做了修改。 在Python 2.x 版本中,示例如下:
for i in range(0,5):
print i
默认情况是自动换行的,如果说是不自动换行,在最后加逗号就可以了:print i,

在Python 3.0 的文档里,对print 说明如下:
print([object, ...], *, sep=' ', end='\n', file=sys.stdout)
Print object(s) to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like str() does and written
to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no object is given, print() will
just write end.
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will
be used.

在Python 3.x 版本中,如果不想自动换行,就需要使用end 参数。该参数默认使用'\n',即回车换行,如果不想使用,换成其他字符,或者为空即可。 示例如下:

>>> for i in range(5):
print(i,end='')

01234
>>> for i in range(5):
print(i)

0
1
2
3
4
>>> for i in range(5):
print(i,end=',')

0,1,2,3,4,

3.2 print 正常输出
使用print输出各型的
(1). 字符串
(2). 整数
(3). 浮点数
(4). 出度及精度控制
>>> str = 'tianlesoftware Oracle dba'
>>> print(str);
tianlesoftware Oracle dba
>>>
3.3 格式化输出整数
python print也支持参数格式化,与C言的printf似, 示例:

>>> str = "the length of (%s) is %d" %('Hello World',len('Hello World'))
>>> print(str)
the length of (Hello World) is 11

或者直接写道print里:
>>> print( "the length of (%s) is %d" %('Hello World',len('Hello World')))
the length of (Hello World) is 11
>>>

3.4 格式化输出16制整数
nHex = 0x20
#%x --- hex 十六进制
#%d --- dec 十进制
#%o --- oct 八进制

示例:
>>> nHex = 0x20
>>> print("nHex = %x,nDec = %d,nOct = %o" %(nHex,nHex,nHex))
nHex = 20,nDec = 32,nOct = 40

3.5 格式化输出浮点数(float)
#导入math 模块
>>> import math
#default
>>> print("PI = %f" % math.pi)
PI = 3.141593
#width = 10,precise = 3,align = left
>>> print("PI = %10.3f" % math.pi)
PI = 3.142
#width = 10,precise = 3,align = rigth
>>> print("PI = %-10.3f" % math.pi)
PI = 3.142
#前面填充字符
>>> print("PI = %06d" % int(math.pi))
PI = 000003
>>>

3.6 格式化输出字符串(string)
#precise = 3
>>> print("%.3s " % ("jcodeer"))
jco
#precise = 4
>>> print("%.*s" % (4,"jcodeer"))
jcod
#width = 10,precise = 3
>>> print ("%10.3s" % ("jcodeer"))
jco

3.7 输出列表(list)
#list直接打印即可
>>> l = [1,2,3,4,'tianlesoftware']
>>> print(l)
[1, 2, 3, 4, 'tianlesoftware']
>>> print(l[0])
1
>>> print(l[4])
tianlesoftware

3.8 输出字典(dictionary)
>>> dave = {1:'A',2:'B',3:'C',4:'D'}
>>> print(dave)
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}
>>> print(dave[4])
D
>>> print(dave[1])
A
四. input 读取输入值
在Python 2.x版本中,使用raw_input,但是到了Python 3.x,转变成input,帮助文档对该方法的说明如下:

input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline),
and returns that. When EOF is read, EOFError is raised.

Example:
>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

4.1. 输入字符串
nID = ''
while 1:
nID = input("Input your id plz:\n")
if len(nID) != len("123456789"):
print('wring length of id,input again')
else:
break

print('your id is %s' % (nID))

4.2.输入整数
nAge = int(input("input your age plz:\n"))
if nAge > 0 and nAge < 120:
print('thanks!')
else:
print('bad age')
print( 'your age is %d\n' % nAge)

4.3. 输入浮点型
fWeight = 0.0
fWeight = float(input("input your weight: \n"))
print('your weight is %f' % fWeight)

4.4. 输入16进制数据
nHex = int(input('input hex value(like 0x20):\n'),16)
print( 'nHex = %x,nOct = %d\n' %(nHex,nHex))

4.5. 输入8进制数据
nOct = int(input('input oct value(like 020):\n'),8)
print ('nOct = %o,nDec = %d\n' % (nOct,nOct))

五. Enumerate 用法

帮助文档说明:
enumerate(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator
returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from iterating over iterable. enumerate() is useful
for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), ....
For example:
>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
... print(i, season)
0 Spring
1 Summer
2 Fall
3 Winter

5.1 在for循环中得到计数
参数为可遍历的变量,如 字符串,列表等;返回值为enumerate类:
import string
s = string.ascii_lowercase
e = enumerate(s)
print(s)
print(list(e))

输出为:
>>>
abcdefghijklmnopqrstuvwxyz
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15, 'p'), (16, 'q'), (17, 'r'), (18, 's'), (19, 't'), (20, 'u'), (21,
'v'), (22, 'w'), (23, 'x'), (24, 'y'), (25, 'z')]
>>>
在同时需要index和value值的时候可以使用 enumerate。

5.2 enumerate 实战
line 是个 string 包含 0 和 1,要把1都找出来:
#方法一
def read_line(line):
sample = {}
n = len(line)
for i in range(n):
if line[i]!='0':
sample[i] = int(line[i])
return sample

#方法二
def xread_line(line):
return((idx,int(val)) for idx, val in enumerate(line) if val != '0')

print( read_line('0001110101'))
print( list(xread_line('0001110101')))

六. yield 用法
The yield expression is only used when defining a generator function, and can
only be used in the body of a function definition. Using a yield expression in a function definition is sufficient to cause that definition to create
a generator function instead of a normal function.
When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of a generator function. The execution starts when one of the generator’s
methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to
generator’s caller. By suspended we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. When the execution is resumed by calling one of the generator’s methods,
the function can proceed exactly as if the yield expression was just another external call. The value of the yield expression
after resuming depends on the method which resumed the execution.
All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. The only difference is that a generator function cannot
control where should the execution continue after it yields; the control is always transferred to the generator’s caller.
The yield statement is allowed in the try clause
of a try ... finally construct.
If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s close() method will be called, allowing any pending finally clauses
to execute.

yield 简单说来就是一个生成器,生成器是这样一个函数,它记住上一次返回时在函数体中的位置。对生成器函数的第二次(或第 n 次)调用跳转至该函数中间,而上次调用的所有局部变量都保持不变。

(1)生成器是一个函数:函数的所有参数都会保留
(2)第二次调用 此函数 时:使用的参数是前一次保留下的.
(3)生成器还“记住”了它在流控制构造:生成器不仅“记住”了它数据状态。 生成器还“记住”了它在流控制构造(在命令式编程中,这种构造不只是数据值)中的位置。由于连续性使您在执行框架间任意跳转,而不总是返回到直接调用者的上下文(如同生成器那样),因此它仍是比较一般的。

yield 生成器的运行机制
当问生成器要一个数时,生成器会执行,直至出现 yield 语句,生成器把 yield 的参数给你,之后生成器就不会往下继续运行。当你问他要下一个数时,他会从上次的状态开始运行,直至出现yield语句,把参数给你,之后停下。如此反复直至退出函数。

6.1 Yield 应用

#生成全排列
def perm(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[:i] + items[i+1:]
for p in perm(rest, n-1):
yield v + p

#生成组合
def comb(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[i+1:]
for c in comb(rest, n-1):
yield v + c

a = perm('abc')
for b in a:
print(b)
break
print('-'*20)
for b in a:
print(b)

a = perm('abc')
for b in a:
print(b)
break
print('-'*20)
for b in a:
print(b)

执行结果:
abc
--------------------
acb
bac
bca
cab
cba
abc
--------------------
acb
bac
bca
cab
cba

在第一个循环break后,生成器没有继续执行,而第二个循环接着第一个循环执行

七. 正则表达式
7.1 字符串替换
7.1.1.替换所有匹配的子串
用newstring替换subject中所有与正则表达式regex匹配的子串
示例:
import re
regex='dba'
newstring='Oracle'
subject='tianlesoftware is dba!'
result,number = re.subn(regex, newstring, subject)
print('the regex result is %s, total change num: %d' %(result,number))

结果:
>>>
the regex result is tianlesoftware is Oracle!, total change num: 1

7.1.2.替换所有匹配的子串(使用正则表达式对象)
reobj = re.compile(regex)
result, number = reobj.subn(newstring, subject)

7.2 字符串拆分
7.2.1.字符串拆分
result = re.split(regex, subject)

7.2.2.字符串拆分(使用正则表示式对象)
import re

regex='tianlesoftware is dba!'

reobj = re.compile(regex)

result = reobj.split('dba')

print('the regex result is %s' %result)

结果:

>>>
the regex result is ['dba']

7.3 匹配
下面列出Python正则表达式的几种匹配用法:
7.3.1.测试正则表达式是否匹配字符串的全部或部分
regex=ur"..." #正则表达式
if re.search(regex, subject):
do_something()
else:
do_anotherthing()

7.3.2.测试正则表达式是否匹配整个字符串
regex=ur"...\Z" #正则表达式末尾以\Z结束
if re.match(regex, subject):
do_something()
else:
do_anotherthing()

7.3.3. 创建一个匹配对象,然后通过该对象获得匹配细节
regex=ur"..." #正则表达式
match = re.search(regex, subject)
if match:
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()
do_something()
else:
do_anotherthing()

7.3.4.获取正则表达式所匹配的子串
(Get the part of a string matched by the regex)
regex=ur"..." #正则表达式
match = re.search(regex, subject)
if match:
result = match.group()
else:
result = ""

7.3.5. 获取捕获组所匹配的子串
(Get the part of a string matched by a capturing group)
regex=ur"..." #正则表达式
match = re.search(regex, subject)
if match:
result = match.group(1)
else:
result = ""

7.3.6. 获取有名组所匹配的子串
(Get the part of a string matched by a named group)
regex=ur"..." #正则表达式
match = re.search(regex, subject)
if match:
result = match.group("groupname")
else:
result = ""

7.3.7. 将字符串中所有匹配的子串放入数组中
(Get an array of all regex matches in a string)
result = re.findall(regex, subject)

7.3.8.遍历所有匹配的子串
(Iterate over all matches in a string)
for match in re.finditer(r"<(.*?)\s*.*?/\1>", subject)
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()

7.3.9.通过正则表达式字符串创建一个正则表达式对象
(Create an object to use the same regex for many operations)
reobj = re.compile(regex)

7.3.10. 用法1的正则表达式对象版本
(use regex object for if/else branch whether (part of) a string can be matched)
reobj = re.compile(regex)
if reobj.search(subject):
do_something()
else:
do_anotherthing()

7.3.11.用法2的正则表达式对象版本
(use regex object for if/else branch whether a string can be matched entirely)
reobj = re.compile(r"\Z") #正则表达式末尾以\Z 结束
if reobj.match(subject):
do_something()
else:
do_anotherthing()

7.3.12.创建一个正则表达式对象,然后通过该对象获得匹配细节
(Create an object with details about how the regex object matches (part of) a string)
reobj = re.compile(regex)
match = reobj.search(subject)
if match:
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()
do_something()
else:
do_anotherthing()

7.3.13.用正则表达式对象获取匹配子串
(Use regex object to get the part of a string matched by the regex)
reobj = re.compile(regex)
match = reobj.search(subject)
if match:
result = match.group()
else:
result = ""

7.3.14.用正则表达式对象获取捕获组所匹配的子串
(Use regex object to get the part of a string matched by a capturing group)
reobj = re.compile(regex)
match = reobj.search(subject)
if match:
result = match.group(1)
else:
result = ""
7.3.15.用正则表达式对象获取有名组所匹配的子串
(Use regex object to get the part of a string matched by a named group)
reobj = re.compile(regex)
match = reobj.search(subject)
if match:
result = match.group("groupname")
else:
result = ""

7.3.16.用正则表达式对象获取所有匹配子串并放入数组
(Use regex object to get an array of all regex matches in a string)
reobj = re.compile(regex)
result = reobj.findall(subject)

7.3.17.通过正则表达式对象遍历所有匹配子串
(Use regex object to iterate over all matches in a string)
reobj = re.compile(regex)
for match in reobj.finditer(subject):
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()

关于正则表达式的规则,参考帮助文档, 这里只列出部分内容:
'.'
(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag
has been specified, this matches any character including a newline.
'^'
(Caret.) Matches the start of the string, and in MULTILINE mode also matches
immediately after each newline.
'$'
Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode
also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ‘foo2’ normally, but ‘foo1’ in MULTILINE mode;
searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.
'*'
Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.
'+'
Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.
'?'
Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’.
*?, +?, ??
The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string,
and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.
{m}
Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six 'a' characters, but not five.
{m,n}
Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m specifies
a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match aaaab or a thousand 'a' characters followed by a b, but not aaab. The comma may not be omitted or the modifier would be confused with the previously
described form.
{m,n}?
Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier.
For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}? will only match 3 characters.
'\'
Either escapes special characters (permitting you to match characters like '*', '?', and so forth), or signals a special sequence; special sequences are discussed below.
If you’re not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn’t recognized by Python’s parser, the backslash
and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it’s highly recommended that you use raw strings
for all but the simplest expressions.
[]
Used to indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a '-'. Special characters
are not active inside sets. For example, [akm$] will match any of the characters 'a', 'k', 'm', or '$'; [a-z] will match any lowercase letter, and [a-zA-Z0-9] matches any letter or digit. Character classes such as \w or \S (defined below) are also acceptable
inside a range, although the characters they match depends on whether ASCII or LOCALE mode
is in force. If you want to include a ']' or a '-' inside a set, precede it with a backslash, or place it as the first character. The pattern []] will match ']', for example.
You can match the characters not within a range by complementing the set. This is indicated by including a '^' as the first character of the set; '^' elsewhere will simply match the '^' character. For example,
[^5] will match any character except '5', and [^^] will match any character except '^'.
Note that inside [] the special forms and special characters lose their meanings and only the syntaxes described here are valid. For example, +, *, (, ), and so on are treated as literals inside [], and backreferences
cannot be used inside [].

\d 匹配任何十进制数;它相当于类 [0-9]。
\D 匹配任何非数字字符;它相当于类 [^0-9]。
\s 匹配任何空白字符;它相当于类 [ \t\n\r\f\v]。
\S 匹配任何非空白字符;它相当于类 [^ \t\n\r\f\v]。
\w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
\W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]。
一. 函数默认值
Python函数默认值的使用可以在函数调用时写代码提供方便,很多时候我们只要使用默认值就可以了。所以函数默认值在python中用到的很多,尤其是在类中间,类的初始化函数中一帮都会用到默认值。使用类时能够方便的创建类,而不需要传递一堆参数。
只要在函数参数名后面加上 '=defalut_value',函数默认值就定义好了。有一个地方需要注意的是,有默认值的参数必须在函数参数列表的最后,不允许将没有默认值的参数放在有默认值的参数后,因为如果你那样定义的话,解释器将不知道如何去传递参数。

示例:
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
flag=True
while flag:
ok = input(prompt)
print(ok)
if ok in ('y', 'yes'):
flag=True
if ok in ('n', 'no'):
flag=False
retries = retries - 1
if retries < 0:
raise IOError
'refusenik user'
print(complaint)

ask_ok('please type in the status(yes/no):')

二. 使用函数默认值来实现函数静态变量的功能
Python中是不支持静态变量的,但是我们可以通过函数的默认值来实现静态变量的功能。
当函数的默认值是内容是可变的类时,类的内容可变,而类的名字没变。(相当于开辟的内存区域没有变,而其中内容可以变化)。
这是因为python中函数的默认值只会被执行一次,和静态变量一样,静态变量初始化也是被执行一次。

看下面的程序片段:
def f(a, L=[]):
L.append(a)
return L

print(f(1))
print(f(2))
print(f(3))
print(f(4,['x']))
print(f(5))

输出:
>>>
[1]
[1, 2]
[1, 2, 3]
['x', 4]
[1, 2, 3, 5]
>>>

最后 “print f(5)”的输出是 “[1, 2, 3, 5]”,因为 “print f(4,['x'])”时,默认变量并没有被改变,因为默认变量的初始化只是被执行了一次(第一次使用默认值调用),初始化执行开辟的内存区(我们可以称之为默认变量)没有被改变,所以最后的输出结果是“[1, 2, 3, 5]”。

三. 多线程
python是支持多线程的,并且是native的线程。主要是通过thread和threading这两个模块来实现的。
python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的,可以更加方便的被使用。
threading模块里面主要是对一些线程的操作对象化了,创建了叫Thread的class。
一般来说,使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里。

3.1 Python thread实现多线程
#-*- encoding: gb2312 -*-
import string, threading, time

def thread_main(a):
global count, mutex
# 获得线程名
threadname = threading.currentThread().getName()

for x in range(0, int(a)):
# 取得锁
mutex.acquire()
count = count + 1
# 释放锁
mutex.release()

print('threadname: %s,threadnum:%d,threadcount:%d\n' %(threadname, x, count))
print('-----\n')
time.sleep(1)

def main(num):
global count, mutex
threads = []

count = 1
# 创建一个锁
mutex = threading.Lock()
# 先创建线程对象
for x in range(0, num):
threads.append(threading.Thread(target=thread_main, args=(2,)))
# 启动所有线程
for t in threads:
t.start()
# 主线程中等待所有子线程退出
for t in threads:
t.join()

if __name__ == '__main__':
num = 4
# 创建4个线程
main(4)

运行结果:
>>>
threadname: Thread-1,threadnum:0,threadcount:2
threadname: Thread-3,threadnum:0,threadcount:4
threadname: Thread-2,threadnum:0,threadcount:3
threadname: Thread-4,threadnum:0,threadcount:5
-----
-----
-----
-----

threadname: Thread-1,threadnum:1,threadcount:6
threadname: Thread-3,threadnum:1,threadcount:7
threadname: Thread-2,threadnum:1,threadcount:8
threadname: Thread-4,threadnum:1,threadcount:9
-----
-----
-----
-----
>>>

3.2 Python threading实现多线程
#-*- encoding: gb2312 -*-
import threading
import time

class Test(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self._run_num = num

def run(self):
global count, mutex
threadname = threading.currentThread().getName()

for x in range(0, int(self._run_num)):
mutex.acquire()
count = count + 1
mutex.release()
print('threadname: %s,threadnum:%d,threadcount:%d\n' %(threadname, x, count))
print('-----\n')
time.sleep(1)

if __name__ == '__main__':
global count, mutex
threads = []
num = 4
count = 1
# 创建锁
mutex = threading.Lock()
# 创建线程对象
for x in range(0, num):
threads.append(Test(2))
# 启动线程
for t in threads:
t.start()
# 等待子线程结束
for t in threads:
t.join()

结果:
>>>
threadname: Thread-1,threadnum:0,threadcount:2
threadname: Thread-3,threadnum:0,threadcount:4
threadname: Thread-2,threadnum:0,threadcount:3
threadname: Thread-4,threadnum:0,threadcount:5
-----
-----
-----
-----
threadname: Thread-1,threadnum:1,threadcount:6
threadname: Thread-3,threadnum:1,threadcount:7
-----
threadname: Thread-2,threadnum:1,threadcount:8
threadname: Thread-4,threadnum:1,threadcount:9
-----
-----
-----
>>>

四. 字符串操作
4.1.连接字符串
def strcat(sStr1,sStr2):
sStr1 += sStr2
return sStr1

print(strcat('strcat','append'))

4.2.查找字符
def strchr(sStr1,sStr2):
nPos = sStr1.index(sStr2)
return nPos

print(strchr('strchr','r'))

4.3.字符串长度
>>> print(len('tianlesoftware'))
14

4.4.将字符串中的小写字符转换为大写字符
>>> sStr1='TianleSoftware'
>>> print(sStr1.upper())
TIANLESOFTWARE
>>> print(sStr1.lower())
tianlesoftware

4.5.追加指定长度的字符串
def strncat(sStr1,sStr2,n):
sStr1 += sStr2[0:n]
return sStr1

print(strncat('12345','abcdef',3))

4.6.将字符串前n个字符替换为指定的字符
def strnset(sStr1,ch,n):
sStr1 = n * ch + sStr1[3:]
return sStr1

print(strnset('12345','r',3))

4.7. 翻转字符串
>>> sStr1 = 'abcdefg'
>>> sStr1 = sStr1[::-1]
>>> print(sStr1)
gfedcba

4.8.查找字符串
>>> sStr1 = 'abcdefg'
>>> sStr2 = 'cde'
>>> print(sStr1.find(sStr2))
2

4.9. 分割字符串
>>> sStr1 = 'ab,cde,fgh,ijk'
>>> sStr2 = ','
>>> sStr1 = sStr1[sStr1.find(sStr2) + 1:]
>>> print(sStr1)
cde,fgh,ijk

五. 列表(List) 操作
5.1 创建列表
sample_list = ['a',1,('a','b')]

5.2 Python 列表操作
sample_list = ['a','b',0,1,3]

5.2.1 得到列表中的某一个值
value_start = sample_list[0]
end_value = sample_list[-1]

5.2.2 删除列表的第一个值
del sample_list[0]

5.2.3 在列表中插入一个值
sample_list[0:0] = ['sample value']

5.2.4 得到列表的长度
list_length = len(sample_list)

5.2.5 列表遍历
for element in sample_list:
print(element)

5.3 Python 列表高级操作/技巧
5.3.1 产生一个数值递增列表
num_inc_list = range(30)
#will return a list [0,1,2,...,29]

5.3.2 用某个固定值初始化列表
initial_value = 0
list_length = 5
sample_list = [ initial_value for i in range(10)]
sample_list = [initial_value]*list_length
# sample_list ==[0,0,0,0,0]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: