Python Forum
Help with removing spaces and tabs from a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with removing spaces and tabs from a string
#1
Could anyone please help me for this question. I am trying to write a program that removes all spaces and tabs from a string that the user gives but I don't want to use any built in functions like replace() e.t.c. Only using while loops, and program outputs the exact string but all spaces and tabs removed.

An example output is:
Input: hi this is a test

Output: hithisisatest
Reply
#2
What have you tried? Post your code in python tags, full traceback in error tags. Ask specific questions - we are glad to help, but we are not going to write your homework.

Also, don't post multiple times the same question and/or hijack threads. I've deleted your post in other user's thread.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thank you for the reply, here is the code that I have. I'm trying to make it so that it checks if there are spaces in a loop and if there are, it removes the space.

newstring =""

string = input("Enter a string: ")

pos = 0

 

length = len(string)

while (pos<len(string)):

 

    if (string[1].isspace()!=True):

            pos = pos + 1

            newstring = newstring + string[pos]

            

            print(newstring)

           

            break
buran write Jan-20-2021, 10:10 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#4
You are updating pos a little too early. When you add one to pos outside of the if statement then your code works as expected.
newstring =""
string = input("Enter a string: ")
pos = 0
length = len(string)
while (pos<length):
	if (string[pos].isspace()!=True):
		newstring = newstring + string[pos]
	pos += 1
print(newstring)
Reply
#5
This helped, thanks so much.
Reply
#6
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.
Marbelous and buran like this post
Reply
#7
And I want to add that string is module from Standard Library, so don't use it as name.
Marbelous likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
Hello, this is actually a follow-up question on my code. So I actually forgot to put my code inside of a function at the start, so I added it in and its saying that its not giving the same output I had before.

string = input("Enter a string: \n")

 

def trim(string):

    newstring = ""

    pos = 0 

    length = len(string)

    

    while (pos < length

       ): 

       if (string[pos].isspace() != True

        ):

        newstring = newstring + string[

            pos] 

    pos += 1 

 

  

 

print(trim(""))
Reply
#9
Please help below code.. output is Mone:

string = input("Enter a string: \n")
def trim(string):
newstring = ""
pos = 0
length = len(string)
while (pos < length
):
if (string[pos].isspace() != True
):
newstring = newstring + string[
pos]
pos += 1
print(trim(""))
Reply
#10
I think you need to read up about Python functions. What did you expect to print. I expected "None" for the code you posted. At least I think that is what I expect since I cannot read your code without indentation. Please use proper tags to wrap your code as requested by buran after you initial post.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I use tabs and spaces? (how to resolve error TabError: inconsistent) Onanism 15 5,858 Mar-24-2022, 07:57 PM
Last Post: Gribouillis
  Tab character in a string prints 8 spaces hecresper 6 20,601 Aug-27-2019, 02:38 PM
Last Post: snippsat
  Removing dublicates from a string JoeNancy 6 3,610 May-20-2018, 12:55 PM
Last Post: JoeNancy
  Removing string within string fivestar 2 3,107 Oct-20-2017, 04:30 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020