Python 查找/切片方法问题
我试图使用find和string切片方法来提取行末尾的数字。但我得到了这个不匹配的错误,因为我回到了位置18,但从我阅读和研究的结果来看,这个位置应该是18,我是不是遗漏了什么Python 查找/切片方法问题,python,Python,我试图使用find和string切片方法来提取行末尾的数字。但我得到了这个不匹配的错误,因为我回到了位置18,但从我阅读和研究的结果来看,这个位置应该是18,我是不是遗漏了什么 str = ('X-DSPAM-Confidence:0.8475') atpos = str.find(':') print atpos sppos = str.find(' ',atpos) print sppos host = float(str[atpos + 1:sppos]) print host 您应
str = ('X-DSPAM-Confidence:0.8475')
atpos = str.find(':')
print atpos
sppos = str.find(' ',atpos)
print sppos
host = float(str[atpos + 1:sppos])
print host
您应该使用
string.split
方法,而不是查找:
分隔符的特定位置
_str = 'X-DSPAM-Confidence:0.8475'
host = float(_str.split(':')[1])
print(host)
str=('X-DSPAM-Confidence:0.8475')
atpos=str.find(“:”)
sppos=str.find(“”,atpos)
host=float(str[atpos+1:]
打印(主机)什么是“此不匹配错误”?您应该避免使用
str
作为标识符,因为它也是字符串类型的名称。(顺便说一句,我对你的代码没有任何问题。)当我运行代码时,我得到这个消息,请更正你的代码并重新运行。我的第一行是18岁← 不匹配我不知道为什么,就像我在阅读和研究中所说的,这是正确的。我还是python新手。我正在python书籍部分做一个练习:6.14练习练习6.5获取以下存储字符串的python代码:“str=”X-DSPAM-Confidence:0.8475“使用查找和字符串切片提取冒号字符后的字符串部分,然后使用float函数转换提取的字符串看起来你的问题不在于Python,而在于某个自动给你的练习打分的工具。我们无法从您提供的信息中了解问题所在。是的,我尝试过,它希望我坚持使用查找方法。但是string.split实际上工作得很好。更一般地说,如果OP位于行的最后一个字段之后,并且行中可能有多个分隔符(即两个以上的字段),host=float(_str.rsplit(':',1)[-1])
可能是一种更好的方法……感谢您提供了这个代码片段,这可能会提供一些有限的、即时的帮助。A通过展示为什么这是一个很好的解决问题的方法,并将使它对未来有其他类似问题的读者更有用。请在您的回答中添加一些解释,包括您所做的假设。
str = ('X-DSPAM-Confidence:0.8475')
atpos = str.find(':')
sppos = str.find(' ',atpos)
host = float(str[atpos + 1:])
print host
text = "X-DSPAM-Confidence: 0.8475";
spacePos = text.find(" ")
number = text[spacePos::1]
#not really necessary but since we are just learning and playing
strippedNumber = number.lstrip();
result = float(strippedNumber)
def reprint(printed):
print printed
reprint(result)