python语法

目录
  1. 语法
    1. 条件判断if/else
    2. 循环
      1. while 语句
      2. for 语句
    3. 推导式
      1. 列表推导式
      2. 字典推导式
      3. 集合推导式
    4. 函数
      1. 匿名lambda函数
  2. 运算符
  3. 字符串操作
    1. 引号
    2. 类型转换
    3. 拼接
    4. 字符串复制
    5. 提取字符
    6. 提取子串
    7. 获取长度
    8. 分割与合并
    9. 文件操作
    10. 二进制转换
    11. python执行shell命令
    12. 其他操作

语法

  • python中使用缩进来区分语句块,而不是c++,java中的{}
  • 条件表达式(if)及函数后面需要加”:”
  • 对于数组变量,其下标从0开始,可以使用array[index, index + n + 1]来取第index - 1 ~ index + n + 1个元素,如array[0,2]代表取array[0]、array[1],注意,这边和stl中的迭代器类似,取得不是是begin到end-1个元素
  • 条件判断与或非:and or not ,而不是c语言的那一套

    条件判断if/else

1
2
3
4
5
6
>>>if condition:
>>> do something
>>>elif condition:
>>> do something
>>>else:
>>> do something

其中,condtion为条件表达式,可以使用逻辑操作符进行判断。

循环

while 语句

1
2
while condition
do something

python 中使用缩进来控制逻辑结构,所以while中有缩进的部分都是while的执行体,其中可以使用break跳出循环或使用continue跳到循环开始

for 语句

1
2
for var in array
do something

经常可以使用zip函数及range函数来生成序列,配合for语句使用:

1
2
3
4
5
6
7
days=['Monday', 'Tuesday']
foods=['chicken', 'beef']
for day, food in zip(days, foods):
print(day, "eat", food)
for x in range(0:3)
print(x)

推导式

推导式是从一个或者多个迭代器快速简洁地创建数据结构的一种方法

列表推导式

  • [expression for item in iterable]
1
2
#number_list = list(range(1,6))等价于
number_list1 = [number for number in range(1,6)]
  • [expression for item in iterable if condition]
1
2
#取16中偶数
number_list1 = [number for number in range(1,6) if number % 2 == 0]

字典推导式

{key_expression : value_expression for expression in iterable }
例子如下:

1
2
3
word = 'letters'
letter_counts = {letter: word.count(letter) for letter in set(word)}
letter_counts

输出结果如下:
{'s': 1, 'r': 1, 'e': 2, 'l': 1, 't': 2}

集合推导式

{expression for expression in iterable}
集合推导式和列表推导式类似,只是[]换成了{}

1
{number for number in range(1, 6)}

函数

函数定义语法:

1
2
3
4
def function_name(arg1, arg2...):
do something
# call function
function_name()

函数中可以指定默认参数.
对于函数参数中*和**特别说明下:

  • *
    星号将一组可变数量的位置参数转换成元组对象
1
2
3
4
5
def print_args(*args):
print('args = ', args)
#call print_args
print_args(3,2,1)

输出结果为 (‘args = ‘, (3, 2, 1))

  • **
    双星号将参数收集到一个字典结构中,参数名为字典的key,参数值为字典的value。
1
2
3
4
5
def print_kwargs(**kwargs):
print("kwargs = ", kwargs)
#call print_kwargs
print_kwargs(china='BJ', britain='London')

输出结果为 (‘kwargs = ‘, {‘britain’: ‘London’, ‘china’: ‘BJ’})

匿名lambda函数

lambda param: operation(param)

tips:
为了读取全局变量而不是函数中的局部变量,需要在变量前面显式地加关键字global

运算符

+,-,,/,%和编程语言一样,特殊的运算符有://(整除)、\*(求幂)

字符串操作

引号

python中可以使用单引号及双引号来表示字符串;另外,可以使用’’’来创建带\n的字符串,如下:

1
2
3
4
5
>>> str='''hello,
... world!'''
>>> print(str)
hello,
world!

类型转换

使用str()可以将其他Python数据类型转换为字符串

拼接

  • 使用 ‘+’ 可以将多个字符串或字符串变量拼接起来,如:
1
2
>>> "hello" + "," + "world"
'hello,world'
  • 或者直接将各个字符串放在一起,如:
1
2
"hello" "," "world"
'hello,world'

字符串复制

使用*可以进行字符串复制,如:

1
2
>>> 'NA'*4
'NANANANA'

提取字符

与c语言类似,可以使用[]运算符来提取指定位置的字符,从左边开始的下标为0;也可以从右边开始,下标从-1开始,依次为-2, -3
当访问越界时会出现异常提示:

1
2
3
4
5
6
7
>>> str1="hello"
>>> str1[0]
'h'
>>> str1[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

提取子串

  • [:]提取从开头到结尾的整个字符串
  • [start:]从start提取到结尾
  • [:end]从开头提取end个字符,即索引为end - 1
  • [start:end]从start提取到end - 1
  • [start:end:step]从start提取到end - 1,每step个字符提取一个

获取长度

使用len()获取字符串长度

分割与合并

  • split()进行字符串分割,默认使用空白符,使用方法如下:
1
2
3
4
5
>>> str="hello, world"
>>> str.split(',')
['hello', ' world']
>>> str.split()
['hello,', 'world']
  • join()用于将字符串合并,用法如下:
1
2
3
4
>>> substr
['hello', ' world']
>>> ','.join(substr)
'hello, world'

文件操作

  • open
  • file.close
  • file.write
  • file.read
  • file.seek
  • file.tell
  • file.readline
  • file.writelines

示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> import os
>>> fp=open("test",'w+')
>>> fp.read()
''
>>> fp.write("hello, world")
>>> fp.tell()
12
>>> fp.read()
''
>>> fp.seek(os.SEEK_SET)
>>> fp.read()
'hello, world'
>>> fp.close()>>> fp.close()

二进制转换

文本字符串 –> 二进制 : binascii.hexlify
二进制 —> 文本字符串 : binascii.unhexlify
示例如下:

1
2
3
4
5
6
7
8
>>> str="fffff"
>>> import binascii
>>> str1=binascii.hexlify(str)
>>> print str1
6666666666
>>> binascii.unhexlify(str1)
'fffff'
>>>

python执行shell命令

  • result=os.popen(command).read() #返回文件描述符,所以可以执行read操作读取结果,相当于fp=os.popen(“command”); fp.read()
  • os.system(“”) #成功返回0
    检查路径是否存在 os.path.exists

    其他操作

  • find()在字符串中查找子串,返回第一个匹配位置的索引,对应的rfind()为最后一个匹配的索引
  • count(word)返回给定word在字符串中的匹配数
  • capitalize()将字符串首字母改成大写
  • upper()将字符串转换为大写
  • lower()将字符串转换为小写
  • swapcase()颠倒大小写
  • replace(oldstr, newstr[, count]) 将oldstr替换成newstr,count参数可以指定,最大替换count个,若未指定,则表示全部替换

tips:
使用python交互环境的话可以使用bpython,具有自动补全及命令提示功能,很适合新手使用

本站总访问量