简体   繁体   中英

Removing first character from string

I am working on a CodeEval challenge and have a solution to a problem which takes a list of numbers as an input and then outputs the sum of the digits of each line. Here is my code to make certain you understand what I mean:

import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
    if test:
        num = int(test)
        total =0
        while num != 0:
            total += num % 10
            num /= 10
        print total


test_cases.close()

I am attempting to rewrite this where it takes the number as a string, slices each 0-index, and then adds those together (curious to see what the time and memory differences are - totally new to coding and trying to find multiple ways to do things as well)

However, I am stuck on getting this to execute and have the following:

import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
    sums = 0
    while test:
      sums = sums + int(str(test)[0])
      test = test[1:]
    print sums

test_cases.close()

I am receiving a "ValueError: invalid literal for int() with base 10: ''"

The sample input is a text file which looks like this:

3011
6890
8778
1844
42
8849
3847
8985
5048
7350
8121
5421
7026
4246
4439
6993
4761
3658
6049
1177

Thanks for any help you can offer!

Your issue is the newlines (eg. /n or /r/n) at the end of each line.

Change this line:

for test in test_cases:

into this to split out the newlines:

for test in test_cases.read().splitlines():

try this code:

tot = 0
with open(sys.argv[1], 'r') as f:
    for line in f:
        try:
            tot += int(line)
        except ValueError:
            print "Not a number"

print tot
  • using the context manager ( with... ) the file is automatically closed.
  • casting to int filter any empty or not valid value

you can substitute print with any other statement optimal for you ( raise or pass depending on your goals)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM