Python第二周作业
Python第二周作业
文章目录
- Python第二周作业
- 编写代码,使用random模块生成一个包含5个随机整数(范围1-100)的列表
- 如何将字符串"hello"转换为元组?写出代码
- 字符串的replace()方法是否会修改原字符串?为什么?请举例说明
- 编写代码,使用random模块生成一个包含5个随机整数(范围1-100)的列表
import random
# 方式一:
random_list = [random.randint(1, 100) for i in range(5)]
print(random_list)# 方式二:
data_list = list(range(1,101))
count = 5
choice_data = random.sample(data_list, count)
print(f"随机抽取列表中{count}个元素:{choice_data}")
- 如何将字符串"hello"转换为元组?写出代码
str = "hello"
tu_str = tuple(str)
print(tu_str)
- 字符串的replace()方法是否会修改原字符串?为什么?请举例说明
在
Python
中,字符串的replace()
方法不会修改原字符串。这是因为字符串在Python
中是不可变对象immutable
,任何对字符串的操作都不会直接改变原字符串,而是返回一个新的字符串