python 基础数据结构简介
1、整型和浮点蕞瞀洒疸型的基本用法与其他语言的使用方法是一样的。基本用法:x = 3print(type(x)) # Prints "<class 'int'>稆糨孝汶;"print(x) # Prints "3"print(x + 1) # Addition; prints "4"print(x - 1) # Subtraction; prints "2"print(x * 2) # Multiplication; prints "6"print(x**2) # Exponentiation; prints "9"x += 1print(x) # Prints "4"x *= 2print(x) # Prints "8"y = 2.5print(type(y)) # Prints "<class 'float'>"print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"
2、上述程序的而运行结果如下:<class 'int'>3426948<class 'float'>2.5 3.5 5.0 6.25
3、Booleans: python 常常使用英文字母来实现逻辑运算,而不是使用操作符&&,||等。使用详解:t = Truef = Falseprint(type(t)) # Prints "<class 'bool'>"print(t and f) # Logical AND; prints "False"print(t or f) # Logical OR; prints "True"print(not t) # Logical NOT; prints "False"print(t != f) # Logical XOR; prints "True"
4、步骤三程序的运行结果如下所示:<class 'bool'>FalseTrueFalseTrue
5、Python支持字符串类型的操作。使用如下:hello = 'hello' # String literals can use single quotesworld = "world" # or double quotes; it does not matter.print(hello) # Prints "hello"print(len(hello)) # String length; prints "5"hw = hello + ' ' + world # String concatenationprint(hw) # prints "hello world"hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formattingprint(hw12) # prints "hello world 12"
6、运行结果:hello5hello worldhello world 12
7、string拥有这许多有用的方法。如下:衡痕贤伎s = "hello"print(s.capitalize()) # Cap足毂忍珩italize a string; prints "Hello"print(s.upper()) # Convert a string to uppercase; prints "HELLO"print(s.rjust(7)) # Right-justify a string, padding with spaces; prints " hello"print(s.center(7)) # Center a string, padding with spaces; prints " hello "print(s.replace('l', '(ell)')) # Replace all instances of one substring with another; # prints "he(ell)(ell)o"print(' world '.strip()) # Strip leading and trailing whitespace; prints "world"
8、运行结果如下:HelloHELLO hellohellohe(ell)(ell)oworld