rxbots rxbots - 3 years ago 166
Python Question

How to get an int from the end of a string seperated by a space that might have more ints in it?

I'm making an "arena" pyton script where users can battle. It reads from "ArenaList.txt" and each string is formatted "username skill", like "wootiown 15" or something like that. I'm trying to find a way to get the int at the end of that string, set that to one int, get the username at the beginning and set it to an str, then be able to change the skill value in the file. Thanks!

Answer Source

How about using str.split? The following code should work (I think, your question isn't very clear):

def getNumber():
    data = []
    with open('ArenaList.txt', 'r') as file:
        for line in file:
            name, number = line.split()
            number = int(number)
            data.append([name, number])
    return data

This creates a new list containing the names and skills of each player. For example, if the file contained

wootiown 15
testing 5

the above function would return

[['wootiown', 15], ['testing', 5]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download