일련의 단어와 공백이 있는 문자열이 주어지면 문자열을 한 번만 탐색하여 모든 공백을 문자열 앞으로 이동하는 것이 작업입니다. 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 program Final Result ::>" pythonprogram"입력