n = input("input n: ")
n.split()
print(n, len(n))
Say the input is: 100 400, seperated by a space, .split() returns a list of all the individual digits, as well as the space between them, instead of the two numbers such that len(n) = 7, and n[0] = 1 instead of 100.
CodePudding user response:
You might get the expected results if you do this:
n = input("input n: ")
n = n.split()
print(n, len(n))
CodePudding user response:
You aren't replacing n
with the return value of n.split()
.
>>> n = "100 400"
>>> n.split()
['100', '400']
>>> n
"100 400"
You need to save that return value.
>>> x = n.split()
>>> print(x, len(x))
['100', '400'] 2
You can, of course, assign the result back to the name n
(although that can cause some issues if you are using mypy
to check your code, as it will infer a static type of str
for n
and complain about an attempt to assign a list to the name).
CodePudding user response:
You're printing the original output of n
and not a list of your original variable split. You need to access your list variable after you've split it:
n = input("input n: ")
after = n.split()
print(after, len(after))
Yields:
['100', '400'] 2
If you wanted to access individual indexes, you could iterate through the list after
and access each index, like so:
n = input("input n: ")
after = n.split()
for x in range(0, len(after)):
print(after[x])
Which yields:
100
400
CodePudding user response:
If you want to split a string by spaces use
n.split(' ')