เมื่อมีสตริงที่มีชุดของคำและช่องว่าง ภารกิจของเราคือย้ายช่องว่างทั้งหมดไปที่ด้านหน้าของสตริง โดยผ่านสตริงเพียงครั้งเดียว เราจะแก้ปัญหานี้อย่างรวดเร็วใน Python โดยใช้ List Comprehension
ตัวอย่าง
Input: string = "python program" Output: string= “ pythonprogram"
อัลกอริทึม
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.
โค้ดตัวอย่าง
# 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) ผลลัพธ์
Enter String python program Final Result ::>" pythonprogram"