ย้าย space ทั้งหมดไปด้านหน้าสตริงโดย遍历เพียงครั้งเดียว ใช้ List Comprehension
ตัวอย่าง
Input: "python program" Output: " pythonprogram"
อัลกอริทึม
- สร้างสตริงไม่มี space:
[c for c in s if c != ' '] - นับจำนวน space:
len(s) - len(no_space) - สร้างผลลัพธ์:
' ' * space_count + ''.join(no_space)
โค้ดตัวอย่าง
def frontstringmove(s):
noSp = [c for c in s if c != ' ']
space = len(s) - len(noSp)
result = ' ' * space + ''.join(noSp)
print("Final Result:", result)
if __name__ == "__main__":
s = input("Enter String: ")
frontstringmove(s)
ผลลัพธ์
Enter String: python program Final Result: pythonprogram