例如
如果输入“小张年龄是26,体重是72.5公斤,身高是1.82m”,则输出26,72.5,1.82
不用函数和正则表达式的程序
我的思路是:遍历整个字符串,判断是数字或者是.的话就暂时存到一个变量temp中,直到遇到下一个非以上两种类型的数据,就将temp添加到结果列表num_list中,这样遍历完成后num_list存储的就是所有的数字类型。代码如下:
s = '小张年龄是26,体重是72.5公斤,身高是1.82m'
num_list = []
temp = ''
for word in s:
if word.isdigit() or word == '.':
temp += word
continue
if temp:
num_list.append(eval(temp))
temp = ''
print(num_list)
执行结果:
有帮助的话,请点采纳该答案~
str = "小张年龄是26,体重是72.5公斤,身高是1.82m"
items = str.split(",") # 使用逗号分割字符串
age_str = items[0].split("是")[1] # 获取年龄字符串并去除“是”字
weight_str = items[1].split("是")[1].replace("公斤", "") # 获取体重字符串并去除“是”字和“公斤”字
height_str = items[2].split("是")[1].replace("m", "") # 获取身高字符串并去除“是”字和“m”字
age = int(age_str) # 将年龄字符串转换为整数
weight = float(weight_str) # 将体重字符串转换为浮点数
height = float(height_str) # 将身高字符串转换为浮点数
print(age, weight, height) # 输出结果