以下是在 Python 中如何使用各种常见数据类型的示例:
一、数字类型(整数、浮点数、复数)
1. 基本运算:
python
a = 10
b = 3
c = a + b # 13
d = a – b # 7
e = a * b # 30
f = a / b # 3.3333333333333335
g = a % b # 1
h = a ** b # 1000
2. 浮点数运算注意精度问题:
python
x = 0.1 + 0.2
print(x) # 0.30000000000000004
3. 复数运算:
python
z1 = 3 + 4j
z2 = 2 – 1j
print(z1 + z2) # (5+3j)
print(z1 * z2) # (10+5j)
二、字符串类型(str)
1. 字符串拼接:
python
s1 = “Hello”
s2 = “World”
s3 = s1 + ” ” + s2
print(s3) # Hello World
2. 字符串格式化:
python
name = “John”
age = 30
s = f”My name is {name} and I am {age} years old.”
print(s) # My name is John and I am 30 years old.
3. 字符串索引和切片:
python
s = “Python is great”
print(s[0]) # P
print(s[2:5]) # tho
三、列表(list)
1. 创建和访问:
python
my_list = [1, 2, 3, “four”, 5.0]
print(my_list[0]) # 1
print(my_list[-1]) # 5.0
2. 添加和删除元素:
python
my_list.append(6)
print(my_list) # [1, 2, 3, ‘four’, 5.0, 6]
my_list.remove(2)
print(my_list) # [1, 3, ‘four’, 5.0, 6]
3. 切片操作:
python
print(my_list[1:3]) # [3, ‘four’]
四、元组(tuple)
1. 创建和访问:
python
my_tuple = (1, 2, 3, “four”, 5.0)
print(my_tuple[2]) # 3
2. 元组不可变:
python
my_tuple[0] = 10 # 会报错,元组不可修改
五、集合(set)
1. 创建和操作:
python
my_set = {1, 2, 3, 4}
my_set.add(5)
print(my_set) # {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set) # {1, 2, 4, 5}
2. 集合运算:
python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.union(set2)) # {1, 2, 3, 4}
print(set1.intersection(set2)) # {2, 3}
print(set1.difference(set2)) # {1}
六、字典(dict)
1. 创建和访问:
python
my_dict = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
print(my_dict[‘name’]) # John
print(my_dict.get(‘age’)) # 30
2. 添加和修改键值对:
python
my_dict[‘
python练习3
小M在工作时遇到了一个问题,他需要将用户输入的不带千分位逗号的数字字符串转换为带千分位逗号的格式,并且保留小数部分。小M还发现,有时候输入的数字字符串前面会有无用的 0,这些也需要精简掉。请你帮助小M编写程序,完成这个任务。 测试样例样例1: 输入:s = “1294512.12412”输出:’1,294,512.12412′ 样例2: 输入:s = “0000123456789.99”输出:’123,456,789.99′ 样例3: 输入:s = “987654321”输出:’987,654,321′ ②