Don't parse integers from strings manually. Python is perfectly capable of doing that for you:
>>> s = "12345"
>>> i = int(s)
>>> print(i)
12345
That already cleans up a substantial part of your code:
string = string.lstrip()
n = int(string)
for i in range(n):
string = string.lstrip()
array[i] = int(string)
I don't see any logic that moves around the string, so I assume you have left those pieces out. You aren't explicit about what exactly it is that separates these integers either (your code says "anything that isn't a digit"), so I'll assume instead it's whitespace-delimited.
Python can split such strings for you through one of the methods in str
: split
.
>>> s = "1 2\n3\t4 5" # Notice: all kinds of whitespace here.
>>> arr = s.split() # By default, split will split on whitespace.
>>> print(arr)
['1', '2', '3', '4', '5']
Notice that the split leaves the values as strings. That means we aren't done yet, we also have to convert each individual element into an integer as I demonstrated before.
Here, I'll use a Python feature called list comprehensions:
>>> s = "1 2\n3\t4 5"
>>> arr = [int(n) for n in s.split()]
>>> print(arr)
[1, 2, 3, 4, 5]
This is what people are talking about when they mention the "expressiveness" of Python :) This turns all of the code you've written into a one-liner. However, this assumes your data is in a string already. It seems you're reading from a file, so there's a bit more work required to get it working properly...
arr = [] # Empty list.
with open("path/to/file.txt") as f:
for line in f: # Will read all lines.
arr += [int(x) for x in line.split()]
# Use arr...
...which assumes you have multiple ints in a line. If instead you have a single int on every line, your code becomes much simpler:
with open("path/to/file.txt") as f:
arr = [int(line) for line in f] # Will read all lines.
# Use arr...
However, this still isn't a complete solution to your original problem... But I hope it's educational regardless. FWIW, this is how I would solve your particular problem:
with open("path/to/file.txt") as f:
ints_of_f = (int(line) for line in f) # A *GENERATOR*, not a *LIST*.
n = next(ints_of_f)
arr = [next(ints_of_f) for _ in range(n)] # _ is a throwaway variable.
Finally, here's a great talk on how to write "beautiful, expressive" Python code.