簡體   English   中英

str 不會轉換為 float/int,因為它沒有像數字那樣忽略 '\\n'

[英]str not converting to float/int because its not ignoring '\n' like it should for a number- python

我正在做一些自學,遇到了這個問題。

def main():

    golf = open('golf.txt','w')

    name = not('end')

    while name != 'end':
        name = input("Enter players name or 'end'  to quit ")
        score = float(input('Enter score '))
    
        golf.write(name + '\n')
        golf.write(str(score) +'\n')
        name = input("Enter players name or 'end'  to quit ")
    
    golf.close()

    golf=open('golf.txt','r')

    name = golf.readline()

    while name !='':
        score = float(golf.readline()) #ValueError#
        name = name.rstrip('\n')
    
    print(name,': ',score)
    golf.close()

main()

Enter players name or 'end'  to quit ted
Enter score 100
Enter players name or 'end'  to quit end
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-b71bcadf2947> in <module>
     27     golf.close()
     28 
---> 29 main()
     30 
     31 

<ipython-input-6-b71bcadf2947> in main()
     21 
     22     while name !='':
---> 23         score = float(golf.readline())
     24         name = name.rstrip('\n')
     25 

ValueError: could not convert string to float: 

********changed float to int below**********

Enter players name or 'end'  to quit ted
Enter score 100
Enter players name or 'end'  to quit end
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-8bffc375cbfa> in <module>
     27     golf.close()
     28 
---> 29 main()
     30 
     31 

<ipython-input-7-8bffc375cbfa> in main()
     21 
     22     while name !='':
---> 23         score = int(golf.readline())
     24         name = name.rstrip('\n')
     25 

ValueError: invalid literal for int() with base 10: '100.0\n'

我為此收到一個 ValueError,我不明白。 如果我將 float 更改為 int,它會讓我更多地了解它無法轉換的內容:'10\\n'。 它似乎沒有像數字那樣忽略逃逸。 嘗試刷新我的內核,但一切仍然一無所獲。 我不應該 rstrip 字符串數字...

如果您有更多錯誤或問題,請嘗試此操作並發布

def main():
    name = ""
    with open("golf.txt", "w") as golf:
        while name != "end":
            name = input("Enter player's name or 'end' to quit: ")
            if name != "end":
                score = input("Enter score: ")
    
                golf.write(name + "\n")
                golf.write(score + "\n")
    
    with open("golf.txt") as golf:
        text = golf.read().split("\n")

    for i in range(0, len(text), 2):
        try:
            name = text[i]
            score = text[i+1]
        except IndexError:
            break
        print(f"{name}: {score}")


main()

f-字符串

使用這些是為了您可以在 python 中的字符串中傳遞變量。 f-strings 是在 python 3.6 中引入的,你可以這樣寫

string = f"Something here {variable}"

# You can also do the same in older versions by using '.format()'
string = "Something here {}".format(variable)

這是一個鏈接,可以從“RealPython”中閱讀有關字符串格式和 f 字符串的更多信息


你可以很多渠道了解。

這是閱讀“GeeksforGeeks”中with關鍵字的鏈接


嘗試/除外

try/except塊捕獲可能發生的錯誤並在發生該錯誤時執行代碼。 所以當i+1大於len(text)時會發生IndexError ,所以為了捕捉我使用了try/except塊。

這是從“W3Schools”閱讀更多相關信息的鏈接


休息

break時,要停止沒有經過執行線運行過早使用循環break聲明。 這里使用它是因為當IndexError發生時,意味着列表被解析並且我們無法打印分數或名稱,因此我們需要退出循環。

這是從“Programiz”閱讀更多相關信息的鏈接


此外ValueError不再發生,因為score變量將始終是一個字符串,因為沒有對其進行計算。 但是,您可以在創建text變量后將其轉換為浮點數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM