繁体   English   中英

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

[英]Removing first character from string

我正在处理CodeEval挑战,并且有一个解决方案来解决此问题,该问题以数字列表作为输入,然后输出每行数字的总和。 这是我的代码,以确保您了解我的意思:

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()

我正在尝试重写此方法,它以数字作为字符串,将每个0索引切成薄片,然后将它们加在一起(很好奇地看到时间和内存的差异是什么-编码的全新知识,并尝试找到多种方法来完成事情)

但是,我坚持让它执行并具有以下功能:

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()

我收到“ ValueError:int()以10为底的无效文字:”

输入的示例是一个文本文件,如下所示:

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

谢谢你的尽心帮助!

您的问题是每行末尾的换行符(例如/ n或/ r / n)。

更改此行:

for test in test_cases:

这样做以换行:

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

试试这个代码:

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

您可以用任何其他最适合您的陈述来代替print (根据您的目标raisepass

暂无
暂无

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

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