Python代码可在单个遍历中将空格移到字符串的开头

我们有一个字符串,我们的目标是将字符串中的所有空格移到前面。假设一个字符串包含四个空格,那么我们必须将这四个空格移动到每个字符的前面。在进行编码之前,让我们看一些示例测试案例。

Input:
string = "nhooo.com "
Output:
"nhooo" -> output will be without quotes


Input:
string = "我是python程序员。"
Output:
"Iamapythonprogrammer." -> output will be without quotes

让我们按照以下步骤实现我们的目标。

算法

1. Initialise the string.
2. Find out all the characters which are not spaces and store them in a variable.
3. Find out the no. of spaces by count method of the string.
4. Multiply a space by no. of spaces and store it in a variable.
5. Append all the characters to the previous variable.
6. Print the result at the end.

让我们尝试实现上述算法。

示例

## initializing the string
string = "nhooo.com "
## finding all character exclusing spaces
chars = [char for char in string if char != " "]
## getting number of spaces using count method
spaces_count = string.count(' ')
## multiplying the space with spaces_count to get all the spaces at front of the ne
w_string
new_string = " " * spaces_count
## appending characters to the new_string
new_string += "".join(chars)
## priting the new_string
print(new_string)

输出结果

如果运行上述程序,将得到以下输出。

nhooo

让我们用不同的输入执行程序。

示例

## initializing the string
string = "我是python程序员。"
## finding all character exclusing spaces
chars = [char for char in string if char != " "]
## getting number of spaces using count method
spaces_count = string.count(' ')
## multiplying the space with spaces_count to get all the spaces at front of the ne
w_string
new_string = " " * spaces_count
## appending characters to the new_string
new_string += "".join(chars)
## priting the new_string
print(new_string)

输出结果

如果运行上述程序,将得到以下输出。

Iamapythonprogrammer.

结论

如果您对该程序有任何疑问,请在评论部分中提及。