python 基础数据结构简介

2025-10-22 17:52:43

1、整型和浮点型的基本用法与其他语言的使用方法是一样的。

基本用法:

x = 3

print(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 += 1

print(x)  # Prints "4"

x *= 2

print(x)  # Prints "8"

y = 2.5

print(type(y)) # Prints "<class 'float'>"

print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"

python 基础数据结构简介

2、上述程序的而运行结果如下:

<class 'int'>

3

4

2

6

9

4

8

<class 'float'>

2.5 3.5 5.0 6.25

python 基础数据结构简介

3、Booleans: python 常常使用英文字母来实现逻辑运算,而不是使用操作符&&,||等。

使用详解:

t = True

f = False

print(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"

python 基础数据结构简介

4、步骤三程序的运行结果如下所示:

<class 'bool'>

False

True

False

True

python 基础数据结构简介

5、Python支持字符串类型的操作。

使用如下:

hello = 'hello'    # String literals can use single quotes

world = "world"    # or double quotes; it does not matter.

print(hello)       # Prints "hello"

print(len(hello))  # String length; prints "5"

hw = hello + ' ' + world  # String concatenation

print(hw)  # prints "hello world"

hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting

print(hw12)  # prints "hello world 12"

python 基础数据结构简介

6、运行结果:

hello

5

hello world

hello world 12

python 基础数据结构简介

7、string拥有这许多有用的方法。

如下:

s = "hello"

print(s.capitalize())  # Capitalize 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"

python 基础数据结构简介

8、运行结果如下:

Hello

HELLO

  hello

 hello 

he(ell)(ell)o

world

python 基础数据结构简介

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢