Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python ย้าย Space ไปหน้าสตริงในครั้งเดียว


ย้าย space ทั้งหมดไปด้านหน้าสตริงโดย遍历เพียงครั้งเดียว ใช้ List Comprehension

ตัวอย่าง

Input: "python program"
Output: " pythonprogram"

อัลกอริทึม

  1. สร้างสตริงไม่มี space: [c for c in s if c != ' ']
  2. นับจำนวน space: len(s) - len(no_space)
  3. สร้างผลลัพธ์: ' ' * 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