Home > Software engineering >  Which index of string is an int in python
Which index of string is an int in python

Time:11-23

I am reading a text file with high scores and trying to find which index of the string is where the name stops, and the score starts. This is the format of the file:

John 15
bob 27
mary 72
videogameplayer99 99
guest 71

How can I do this?

CodePudding user response:

If you are looking to find the index to split the string into 2 separate parts, then you can just use [string].split() (where string is an individual line). If you need to find the index of the space for some other reason, use: [string].index(" ").

CodePudding user response:

You can strip the line to separate it by the space. It will result in a list containing the 2 'words' in the line, in this case the words will be the name and the score (in string). You can get it using:

result = line.split()
name = result[0]
score = int(result[1])

CodePudding user response:

In this case, for each line, you would be looking for the index where you first find the space character " ". In python, you can accomplish this by using the find function on a string. For example, if you have a string s = videogameplayer99 99, then s.find(" ") will return `17'.

If you are using this method to split a name from a number, I would instead recommend using the split function, which will split a string based on some delimiter character. For example, s.split(" ") = ["videogameplayer99", "99"].

  • Related