Python程序以单次遍历将空格移到字符串的开头
给定一个包含单词和空格的字符串,我们的任务是通过仅遍历字符串一次将所有空格移到字符串的开头。我们将使用List Comprehension在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 programFinal Result ::>" pythonprogram"
以上是 Python程序以单次遍历将空格移到字符串的开头 的全部内容, 来源链接: utcz.com/z/353476.html