-1

Let's say I have a txt file like such:

I am a Noob:10
You are a Noob:20
He is a Noob:30

What I want to do is get the number after the : for a specific string, let's say for "You are a Noob" without having to know the position that this line is in.

I've found part of the solution in order to find the desired line, like so:

iamnoob = input('You are a Noob')
myFile = open(path).readline()
for line in myFile:
   if iamnoob == line[0]:
      two_parts = line.split(':')[-1]
      print(two_parts)

but I am stuck in how to split it and get the part that I want. Thank you in advance for your assistance.

edit: I only want to keep the number after the split, not the whole line.

  • 1
    That "part of the solution" makes no sense whatsoever. Did you just throw together random things hoping noone would notice? – superb rain Dec 25 '20 at 20:09
  • @mkrieger1 Not really because I don't want the whole line, I just want to keep the number after the split. – Tedd Xanthos Dec 25 '20 at 20:11
  • You asked how to split a line. That other question shows you. – mkrieger1 Dec 25 '20 at 20:13
  • @mkrieger1 I apologize if I wasn't clear enough. I know how to split the line, I don't know how to only keep the second part of the line after the delimiter. – Tedd Xanthos Dec 25 '20 at 20:15
  • Are you aware that splitting the line gives you a list and that you can access individual list elements by using indexing? – mkrieger1 Dec 25 '20 at 20:16
  • 1
    Stack Overflow is not a replacement for spending 10 minutes with an introductory tutorial. – Mad Physicist Dec 25 '20 at 20:20
  • @mkrieger1 I tried print(line[-1]) but it doesn't work as expected. Maybe I've done something wrong? – Tedd Xanthos Dec 25 '20 at 20:21
  • This looks like you didn't use `split` to split the line. – mkrieger1 Dec 25 '20 at 20:22
  • @mkrieger1 Check edited code please. This returns: You are a Noob And I want it to return: 20 – Tedd Xanthos Dec 25 '20 at 20:34
  • It prints `You are a noob` because of `input('You are a noob')`. It doesn't print anything else because the rest of the code doesn't make sense. Read this to learn how to find out why: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – mkrieger1 Dec 25 '20 at 20:40

1 Answers1

1

Once you found the line, split it with the ":" delimiter and take the second part which is the number

line = "I am a Noob:10"
two_parts = line.split(':')
number = int(two_parts[1])
Sami
  • 117
  • 1
  • 3