简体   繁体   English

Python 浮动替换多个

[英]Python Float and Replace More Than One

I will straight to the point.我会直截了当。

First I have an exam scores like this: ( The scores as string )首先,我有这样的考试成绩:(分数为字符串)

  1. Student A: "550.4" -> "."学生 A:“550.4”->“。” = point = 点
  2. Student B: "1,098.9" -> ","(coma) = thousand symbol, "."学生 B:"1,098.9" -> ","(coma) = 千位符号,"." = point = 点
  3. Student C: "1,100.00" -> ","(coma) = thousand symbol, "."学生 C: "1,100.00" -> ","(coma) = 千位符号, "." = point = 点
  4. Student D: "999.99" -> "."学生 D:“999.99”->“。” = point = 点

Criteria:标准:

  1. When a score equal to or less than 600.00, then display "Study more!"当分数等于或小于 600.00 时,则显示“学习更多!”
  2. score <= 600, display "Study more!"分数 <= 600,显示“多学习!”
  3. When a score equal to or more than 1,000.00 (thousand), then display "Get your reward!"当分数等于或大于 1,000.00(千)时,则显示“获得您的奖励!”
  4. score => 1,000.00, display "Get your reward!"得分 => 1,000.00,显示“获得奖励!”

What I want is when one of the students score's meet one of the criteria then display a special messages.我想要的是当其中一名学生的分数满足其中一个标准时,然后显示一条特殊消息。 So to compare the scores with criteria I use this code ( code below ):因此,为了将分数与标准进行比较,我使用了这段代码(下面的代码):

'''
SA = "550.40"
SB = "1,098.90"
SC = "1,100.00"
SD = "999.99"

SA = float(SA) #return 550.4 (as number)
SB = float((SB[0:8]).replace(',','.')) #return error : 'ValueError: could not convert string to float: 1,098.90'
SC = float((SC[0:8]).replace(',','.')) #return error : 'ValueError: could not convert string to float: 1,100.00'
SD - float(SD) #return 999.99 (as number)
'''

Note: I use [0:8] in hope all the score value (as string) will be convert to score(as number, float) If [0:8] does not get all the score value then please correct me注意:我使用 [0:8] 希望所有分数值(作为字符串)都将转换为分数(作为数字,浮点数)如果 [0:8] 没有得到所有分数值,请纠正我

Whenerver I use "replace(',','.')" and meet this condition "XX,XXX.XX" (XX-coma-XXX-point-XX) I will get those Error, and I don't know why.当我使用 "replace(',','.')" 并满足此条件 "XX,XXX.XX" (XX-coma-XXX-point-XX) 时,我会得到那些错误,我不知道为什么.

Please help me.请帮我。 Thank you.谢谢你。

Your replacement results in a string with multiple periods: you can only have one (decimal) period.您的替换会产生一个包含多个句点的字符串:您只能有一个(十进制)句点。 You would need to replace the comma with nothing (empty string), or possibly an underscore (for readability, but that doesn't matter here, since the intermediate result isn't shown):您需要将逗号替换为空字符串(空字符串)或下划线(为了便于阅读,但这并不重要,因为未显示中间结果):

SB = "1,098.90"
SC = "1,100.00"

SB = float(SB[:8].replace(',', ''))
SC = float(SC[:8].replace(',', ''))

You should replace it with empty string instead of ".".您应该将其替换为空字符串而不是“。”。 You also do not need to slice SB and SC .您也不需要切片SBSC

SB = "1,098.90"
SC = "1,100.00"

SB = float(SB.replace(',',''))
SC = float(SC.replace(',',''))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM