
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to move spaces to front of string in single traversal
Given a string that has set of words and spaces, our task is to move all spaces to front of string, by traversing the string only once. We will solve this problem quickly in Python using List Comprehension.
Example
Input: string = "python program" Output: string= “ pythonprogram"
Algorithm
Step1: input a string with word and space. Step2: Traverse the input string and using list comprehension create a string without any space. Step 3: Then calculate a number of spaces. Step 4: Next create a final string with spaces. Step 5: Then concatenate string having no spaces. Step 6: Display string.
Example Code
# Function to move spaces to front of string # in single traversal in Python def frontstringmove(str): noSp = [i for i in str if i!=' '] space= len(str) - len(noSp) result = ' '*space result = '"'+result + ''.join(noSp)+'" print ("Final Result ::>",result) # Driver program if __name__ == "__main__": str = input("Enter String") frontstringmove(str)
Output
Enter String python program Final Result ::>" pythonprogram"
- Related Articles
- Python code to move spaces to the front of string in a single traversal
- Python program to count the number of spaces in string
- Python Program to move numbers to the end of the string
- Move string capital letters to front maintaining the relative order - JavaScript
- Python Program to Replace the Spaces of a String with a Specific Character
- Program to find lexicographically smallest string to move from start to destination in Python
- How to expand tabs in string to multiple spaces in Python?
- C# Program to split a string on spaces
- C++ Program to remove spaces from a string?
- Program to rearrange spaces between words in Python
- C++ program to remove spaces from a string using String stream
- C program to remove extra spaces using string concepts.
- How to replace multiple spaces in a string using a single space using Java regex?
- C# program to replace all spaces in a string with ‘%20’
- C program to remove spaces in a sentence using string concepts.

Advertisements