2
I’m new to python programming. I came across today the challenge of picking up a vector (ex:V1== ['MESA 11 22 33 44 ']) in which all its elements are in string format (as if they were one, only separated by space). The question is to separate this vector so that it stays in this format: V1==['MESA', 1, 2, 3, 4], where I keep the word MESA as string and the other numbers I convert to integer. I tried it this way: first I tried to turn each string with split() into an index.
for i, vetor in enumerate(V1):
V1[i].append(vetor[i].split())
print(V1)
After that, I created another vector(V2) to receive the V1 converted to int. Thus, I created an IF so that if at the current position is the word "TABLE", it adds the contents of V1 in V2 without having to convert to int, and if it is different from that, the index will be converted to a number in, int format.
V2=[]
for i in range(len(V1)):
if V1[i] == 'MESA':
V2[i]= V1[i]
else:
V2[i].append((int(V1[i]))
print(V2)
I don’t know if my problem is in my logic, but I can’t get the syntax right. I appreciate if anyone can help!
the result expected by the user is
['MESA', 1, 2, 3, 4]
. To achieve this result we must useround(int(k) / 11)
instead ofint(k)
.– Solkarped
Thank you @Solkarped . My lack of attention. I will fix
– Lucas
Thank you really, helped a lot hehe. I was extremely confused on this, now I understand and I will read the material!
– Mona -
Imagine. If this answer solved your problem and there is no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved.
– Lucas
Just one more question, if you don’t mind. If the number is negative, for example, would I have to do a function with Try and ecxept so I can convert them? Since isdigit() does not consider the sign "-"
– Mona -
In that case, just replace the probation with
k.replace("-","").isdigit()
– Lucas