简体   繁体   English

从字符串中删除第一个字符

[英]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. 我正在处理CodeEval挑战,并且有一个解决方案来解决此问题,该问题以数字列表作为输入,然后输出每行数字的总和。 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) 我正在尝试重写此方法,它以数字作为字符串,将每个0索引切成薄片,然后将它们加在一起(很好奇地看到时间和内存的差异是什么-编码的全新知识,并尝试找到多种方法来完成事情)

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: ''" 我收到“ ValueError:int()以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. 您的问题是每行末尾的换行符(例如/ n或/ r / n)。

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. 使用上下文管理器( with... )将自动关闭文件。
  • casting to int filter any empty or not valid value 强制转换为int过滤任何空值或无效值

you can substitute print with any other statement optimal for you ( raise or pass depending on your goals) 您可以用任何其他最适合您的陈述来代替print (根据您的目标raisepass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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