Python 程式:一次遍歷將空格移到字串最前


給定一個包含一組單詞和空格的字串,我們的任務是遍歷一次字串,將所有空格移到字串最前面。我們使用列表推導在 Python 中快速解決這個問題。

示例

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"

更新日期: 2020-06-23

413 次瀏覽

開啟你的 職業生涯

完成課程認證

開始入門
廣告
© . All rights reserved.