This is generally frowned upon as a way to iterate.
pos = 0
length = len(string)
while (pos<len(string)):
Do you want length? Do you care about pos? No, these are only used being used to get what you really want, the characters from string. Instead of using a while loop with an index and a length you can get the characters directly using the iterator that is built into str.
for char in string:
if (char.isspace()!=True):
This is generally frowned upon as a way to test:
if (char.isspace()!=True)
You wouldn't think of doing this:
if (a + b == 2) is True:
So why is it ok to do so with a function that returns True or False?
True and False should rarely be used, and should almost never appear in a comparison. char.isspace() returns True or False which are the type of things you need for an if statement. There is no need to use != True go get a logic value. If char.isspace() returns the wrong value for you program logic use "not" to invert the value.
for char in string:
if (not char.isspace()):
Use of extra parenthesis is frowned upon. Python is not C and does not require parentheses surrounding the expression in an if statement.
for char in string:
if not char.isspace():
Building up strings 1 character at a time is not considered a best practice.
newstring = newstring + string[pos]
Each time you execute this statement Python makes a brand new string and deletes the old string. The code works, but it requires a lot of work to work. If you had to do this kind of thing a lot or for a very large string it would be slow.
The way this kind of thing is typically done in Python is to collect all the characters in a list, then use str.join() to put all the characters back together.
string = input("Enter a string: ")
newstring = []
for char in string:
if not char.isspace():
newstring.append(char)
newstring = ''.join(newstring)
print(newstring)
Unlike strings, lists are mutable in Python. Appending to a list does not require creating a new list and deleting the old list. Lists are also very efficient in Python. They have to be because lists and dictionaries are used everywhere.
And finally, using a loop is somewhat frowned upon when the logic can be cleanly encapsulated in a comprehension.
string = input("Enter a string: ")
newstring = ''.join([char for char in string if not char.isspace()])
print(newstring)
Comprehensions have some performance gain over using a for loop. A comprehension also makes it very clear that the result you want is a list (or a dictionary. There are dictionary comprehensions too). A Python coder will see the comprehension and know immediately that the purpose of the code is to make a list. This is clearer than having to read the code in a for loop. Note that "immediately" and "clearer" only apply for a simple comprehension with few loops and filters. A comprehension that is hundreds of characters long is not immediately clear and should be expanded out to regular for loops.