Practical Python基础1(数据类型,运算,比较符号,字符串,列表,函数等)

Practical Python基础1(数据类型,运算,比较符号,字符串,列表,函数等)

Python是一种解释性的高级编程语言。它通常被归类为“脚本语言”,被认为类似于Perl、Tcl或Ruby等语言。Python的语法大致受到C编程元素的启发。

Python程序总是在解释器中运行。python程序是一系列语句:每条语句都以换行符结束。语句一个接一个地执行,直到控件到达文件末尾。

注释是不会执行的文本。

shell中是交互式模式,当开始键入语句,它们将立即运行。没有编辑/编译/运行/调试周期。

  • 设置http代理服务器
import os
os.environ['HTTP_PROXY'] = 'http://yourproxy.server.com'
  • 下划线_保存最后一个结果,只在交互模式正确
>>> 37 * 42
1554
>>> _ * 2
3108
>>> _ + 50
3158
>>>
  • 变量是值的名称,可以使用从a到z的字母(小写和大写)以及字符下划线_。数字也可以是变量名称的一部分,但第一个字符除外。
height = 442 # valid
_height = 442 # valid
height2 = 442 # valid
2height = 442 # invalid
  • Python是动态类型的。当程序执行时,变量的感知“类型”可能会根据分配给它的当前值而改变。区分大小写,语言语句总是小写;缩进用于表示一起出现的语句组;使用空格而不是制表符;每层使用4个空格;使用Python感知编辑器;Python的唯一要求是同一块中的缩进保持一致。
if a > b:
    print('Computer says no')
elif a == b:
    print('Computer says yes')
else:
    print('Computer says maybe')

python print()打印多值,单值,自动末尾添加换行符,可以使用end抑制换行符。

print('Hello', end=' ')
print('My name is', 'Jake')

# Hello My name is Jake
  • input()输入,pass语句指定一个空代码块。关键字pass用于它。
    Python有4种类型的数字:布尔值、整数、浮点、复数(虚数)
x + y      Add
x - y      Subtract
x * y      Multiply
x / y      Divide (produces a float)
x // y     Floor Divide (produces an integer)
x % y      Modulo (remainder)
x ** y     Power
x << n     Bit shift left
x >> n     Bit shift right
x & y      Bit-wise AND
x | y      Bit-wise OR
x ^ y      Bit-wise XOR
~x         Bit-wise NOT
abs(x)     Absolute value

import math
a = math.sqrt(x)
b = math.sin(x)
c = math.cos(x)
d = math.tan(x)
e = math.log(x)

x < y      Less than
x <= y     Less than or equal
x > y      Greater than
x >= y     Greater than or equal
x == y     Equal to
x != y     Not equal to

and  or  not
  • 转换数字
a = int(x)    # Convert x to integer
b = float(x)  # Convert x to float

a = 3.14159
int(a)
# 3

b = '3.14159' # It also works with strings containing numbers
float(b)
# 3.14159
  • 字符串,单引号,双引号,三重引号(括起来的多行文本都是字符串)
  • 转义码用于表示控制字符和不能在键盘上直接键入的字符。以下是一些常见的转义码:
'\n'      Line feed
'\r'      Carriage return
'\t'      Tab
'\''      Literal single quote
'\"'      Literal double quote
'\\'      Literal backslash
  • 字符串的工作方式类似于访问单个字符的数组。使用整数索引,从0开始。负索引指定相对于字符串结尾的位置。还可以使用:分割或选择指定索引范围的子字符串。yang
    连接,长度,成员资格和复制
    删除串前串尾空格,大小写转换,文本替换以及其他很多函数
    字符串可变性,字符串是“不可变”或只读的。一旦创建,值就不能更改,对字符串的操作每次都会创建一个全新的字符串。重新分配变量名符号时,它将指向新创建的字符串。之后旧字符串被销毁,因为它不再被使用。
    所有操作字符串数据的操作和方法都会创建新字符串
    一个8位字节的字符串,通常在低级I/O中遇到

    data=b’你好世界\r\n’
    通过在第一个引号前放一个小b,可以指定它是字节字符串,而不是文本字符串

    转换为文本字符串/从文本字符串转换
    使用in运算符检查子字符串
    symbols.lower() 与 c = symbols.lower() 结果不一致

    dir()生成可以出现在(.)之后的所有操作的列表。使用help()命令获取有关特定操作的详细信息:help(s.upper)

a = 'Hello world'
b = a[0]          # 'H'
c = a[4]          # 'o'
d = a[-1]         # 'd' (end of string)

d = a[:5]     # 'Hello'
e = a[6:]     # 'world'
f = a[3:8]    # 'lo wo'
g = a[-5:]    # 'world'

# Concatenation (+)
a = 'Hello' + 'World'   # 'HelloWorld'
b = 'Say ' + a          # 'Say HelloWorld'

# Length (len)
s = 'Hello'
len(s)                  # 5

# Membership test (`in`, `not in`)
t = 'e' in s            # True
f = 'x' in s            # False
g = 'hi' not in s       # True

# Replication (s * n)
rep = s * 5             # 'HelloHelloHelloHelloHello'

# stripping any leading / trailing white space.
s = '  Hello '
t = s.strip()     # 'Hello'

# Case conversion.
s = 'Hello'
l = s.lower()     # 'hello'
u = s.upper()     # 'HELLO'

# Replacing text.
s = 'Hello world'
t = s.replace('Hello' , 'Hallo')   # 'Hallo world'

s.endswith(后缀) #检查字符串是否以后缀结尾
s.find(t) #t在s中首次出现
s.index(t) #t在s中首次出现
s.isalpha()) #检查字符是否为字母
s.isdigit()#检查字符是否为数字
s.islower() #检查字符是否为小写
s.isupper()#检查字符是否为大写
s.join(slist)#使用s作为分隔符连接字符串列表
s.lower() #转换为小写
s.replace(,) #替换文本
s.rfind(t) #从字符串结尾搜索t
s.rindex(t) #从字符串末尾搜索t
s.split([delim]) #将字符串拆分为子字符串列表
s.startswith(prefix) #检查字符串是否以前缀开头
s.strip() #删除前导/尾随空格
s.upper() #转换为大写


# 转换为文本字符串/从文本字符串转换
text=data.decode('utf-8') #字节->文本
data=text.encode('utf-8') #text->字节

s = 'hello'
print(dir(s))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

print(s.upper)
  • 基本字符串操作的一个限制是它们不支持任何类型的高级模式匹配。为此需要转向Python的re模块和正则表达式。 正则表达式处理是一个很大的主题,但这里有一个简短的示例:
import re

text = 'Today is 3/27/2018. Tomorrow is 3/28/2018.'

# 查找日期的所有事件
print(re.findall(r'\d+/\d+/\d+', text))
# ['3/27/2018', '3/28/2018']

# 用替换文本替换所有出现的日期
print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text))
# Today is 2018-3-27. Tomorrow is 2018-3-28.
  • Lists Python用于保存有序值集合的主要类型。
    如果元素出现多次,index()将返回第一次出现的索引,如果找不到元素,它将引发ValueError异常。
    删除remove()不会创建孔。其他项目将向下移动以填充腾出的空间。如果元素出现多次,remove()将仅删除第一次出现的元素。
    就地排序,sort(),反向排序 sort(reverse=True) 注意:对列表进行排序将修改其内容“就地”。也就是说,列表中的元素被打乱,但不会因此创建新的列表。
    成员测试,in 和 not in
    某个词计数:s.count(“yoho”)
    获取字符串列表并将它们连接到一个字符串中:‘,’.join(s)
    列表可以包含任何类型的对象,包括其他列表(例如嵌套列表),通过使用多个索引操作,可以访问嵌套列表中的项。
s = [10, 1, 7, 3]
s.sort()                    # [1, 3, 7, 10]

# Reverse order
s = [10, 1, 7, 3]
s.sort(reverse=True)        # [10, 7, 3, 1]

# It works with any ordered data
s = ['foo', 'bar', 'spam']
s.sort()                    # ['bar', 'foo', 'spam']

# 使用sorted()创建一个新列表
t = sorted(s)               # s unchanged, t holds sorted values
  • 文件应该正确关闭,这是一个容易忘记的步骤。因此,首选的方法是这样使用with语句。逐行读取,写入文件,print重定向
    读取压缩文件gzip库
f = open('foo.txt', 'rt')     # Open for reading (text)
g = open('bar.txt', 'wt')     # Open for writing (text)

# 读取所有数据
data = f.read()


with open(filename, 'rt') as file:
  # pass
  # 一次将整个文件读入
  data = file.read()

import gzip
with gzip.open('Data/portfolio.csv.gz', 'rt') as f:
  for line in f:
    print(line, end='')
  • 函数是一系列执行任务并返回结果的语句。return关键字需要显式指定函数的返回值
  • 异常处理及抛出异常
for line in file:
    fields = line.split(',')
    try:
        shares = int(fields[1])
    except ValueError:
        print("Couldn't parse", line)
        raise RuntimeError('What a kerfuffle')
  • 使用库函数:Python附带了一个大型的标准函数库如csv模块
import csv

f = open('Data/portfolio.csv')
rows = csv.reader(f)
headers = next(rows)
print(headers)
# ['name', 'shares', 'price']
for row in rows:
   print(row)

# ['AA', '100', '32.20']
# ['IBM', '50', '91.10']
# ['CAT', '150', '83.44']
# ['MSFT', '200', '51.23']
# ['GE', '95', '40.37']
# ['MSFT', '50', '65.10']
# ['IBM', '100', '70.44']
f.close()

参考

猜你喜欢

转载自blog.csdn.net/qq_40985985/article/details/129298586