主要函数为print(),基础调用为:python
myName = "wayne" myAge = 18 print("My name is %s, I'm %d years old." % (myName,myAge)) #"My name is wayne, I'm 18 years old."
经常使用占位符有:%d(整数)、%f(浮点数)、%s(字符串)、%x(十六进制整数)编辑器
print()函数里将逗号","视为一个空格来拼接输出结果:函数
print("I'm",10+8,"years old.") #"I'm 18 years old."
也能够用format()函数来作格式化输出:编码
print("图片\"{0}\"下载百分比为{1:.2f}%".format("1.jpg", 100*0.7/1.5)) # 图片"1.jpg"下载百分比为46.67%
主要函数为input(),基础调用为:code
myName = input("please input your name:") myAge = input("please input your age:") print("My name is %s, I'm %d years old." % (myName,int(myAge)))
与其它语言的字符串大体相似,有几个专有特性:orm
(1) "r"之后的字符串不转义图片
str1 = "AA\nB\"BC\"C" str2 = r"AA\nB\"BC\"C" print(str1) print(str2) ''' AA B"BC"C AA\nB\"BC\"C '''
(2) 多行字符串用'''
来表示utf-8
str1 = '''A B C''' print(str1) ''' A B C '''
顾名思义就是只取整数的除法,示例:ci
print(10/3) print(10//3) ''' 3.3333333333333335 3 '''
python的变量是动态类型的,根据赋值来决定类型,空值用None
表示字符串
intA = 5 intB = intA intA = 10 print(intA,intB) # 10 5 strA = "AAA" strB = strA strA = None print(strA,strB) # None AAA
查询单个字符的整数表示,用ord()
函数;经过数字编码还原单个字符,用chr()
函数
print(ord("a")) # 97 print(chr(65)) # 'A'
也能够直接用ASCII码的形式表示字符或字符串
print('\u9177') # 酷 print('\u4e2d\u56fd') # 中国
字符串经过encode()
方法编码为指定规则的bytes
。
英文与数字构成的字符串通过ASCII编码为bytes
后,内容是同样的;含有中文的字符串用ASCII编码会报错,由于中文编码超过了ASCII编码的范围,应该使用UTF-8来编码
print("ABC123".encode("ascii")) # b'ABC123' print("乐呵呵".encode("utf-8")) # b'\xe4\xb9\x90\xe5\x91\xb5\xe5\x91\xb5'
bytes
经过decode()方法解码为指定规则的字符串。
当bytes里包含无效字节时,直接decode会报错,能够传入errors="ignore"来忽略错误的字节
print(b'ABC123'.decode("ascii")) # ABC123 print(b'\xe4\xb9\x90\xe5\x91\xb5\xe5\x91\xb5'.decode("utf-8")) # 乐呵呵 print(b'\xe4\xb9\x90\x88'.decode("utf-8", errors="ignore")) # 乐
len()
函数用于计算字符或字节数,取决于参数是字符仍是bytes
print(len("ABC")) # 3 print(len(b"ABC")) # 3 print(len("中国")) # 2 print(len("中国".encode("utf-8"))) # 6
在python代码开头加上这两行:
#!/usr/bin/env python3 # -*- coding: utf-8 -*-
第一行注释是告诉Linux和Mac OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释。 第二行注释是告诉Pythonj解释器,按照UTF-8编码读取源代码,不然源代码中的汉字会输出乱码。除了加入语句,还应该保证文本编辑器用UTF-8 without BOM编码。