欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python简明教程_02

程序员文章站 2022-05-28 20:25:15
...

python编程语言简明教程,翻译自以下仓库:
Python-Lectures
原仓库是一系列的jupyter notebook,可以直接在jupyter环境下运行程序示例。我添加了中文注释,并改为了兼容python3

Print: 打印

print 用法(注意python3中必须加括号):

- print("Hello World")
- print("Hello", <Variable Containing the String>)
- print("Hello" + <Variable Containing the String>)
- print("Hello %s" % <variable containing the string>)
print("Hello World")

Hello World

注意引号的使用,一般来讲,单个词用单引号,一行字用双引号,一段话用三个双引号

print('Hey')

Hey

print("""My name is Rajath Kumar M.P.

I love Python.""")

My name is Rajath Kumar M.P.

I love Python.

string1 = 'World'
print('Hello', string1)

string2 = '!'
print('Hello', string1, string2)

(‘Hello’, ‘World’)
(‘Hello’, ‘World’, ‘!’)

print('Hello' + string1 + string2)

HelloWorld!

print("Hello %s" % string1)

Hello World

类似还有其他的数据输出符号:

- %s -> string 字符串
- %d -> Integer 整数
- %f -> Float 浮点
- %o -> Octal 八进制 
- %x -> Hexadecimal 十六进制
- %e -> exponential 科学计数法
print("Actual Number = %d" %18)
print("Float of the number = %f" %18)
print("Octal equivalent of the number = %o" %18)
print("Hexadecimal equivalent of the number = %x" %18)
print("Exponential equivalent of the number = %e" %18)

Actual Number = 18
Float of the number = 18.000000
Octal equivalent of the number = 22
Hexadecimal equivalent of the number = 12
Exponential equivalent of the number = 1.800000e+01

输出好几个变量时,用小括号:

print("Hello %s %s" %(string1,string2))

Hello World !

一些其他例子

print("I want %%d to be printed %s" %'here') # 输出百分号

I want %d to be printed here

print('_A'*10)

_A_A_A_A_A_A_A_A_A_A

print("Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug") #换行

Jan
Feb
Mar
Apr
May
Jun
Jul
Aug

print("I want \\n to be printed.") #输出反斜杠

I want \n to be printed.

print("""
Routine:
\t- Eat
\t- Sleep\n\t- Repeat
""")
Routine:
     - Eat
     - Sleep
     - Repeat

精度输出

python中默认精度为6位:

"%f" % 3.121312312312

‘3.121312’

规定输出几位:

"%.5f" % 3.121312312312

‘3.12131’

超出数字本身的范围,会自动调整

"%9.5f" % 3.121312312312
 '  3.12131'

前面加0,将不够的位数用0补足:

"%020.5f" % 3.121312312312 #一共输出20位,小数点后5位,但小数点前只有一个3,其余位置用0补足

‘00000000000003.12131’

前面留一个空格用来对齐

print("% 9f" % 3.121312312312)
print("% 9f" % -3.121312312312)
  3.121312
 -3.121312

给正数加一个’+’

print("%+9f" % 3.121312312312)
print("% 9f" % -3.121312312312)

+3.121312
-3.121312

"%-9.3f" % 3.121312312312 #负号加到这个位置,表示一共9位,保留小数点后3位,将超出范围的空格放在最后
 '3.121    '

上一篇: pymongo

下一篇: [python]NLTK简明教程