在Python中,如何在给定字符串的左右两侧不使用任何前导空格的情况下生成新字符串字符串的



侧,或基于第二个参数在字符串右侧试用空格。我们不允许使用lstrip/rstrip或任何内置的字符串方法。。

我把右边倒了,但我在左边挣扎。我的代码出了什么问题?

def strip(given: str, direction: str) -> str:
starting_string: str = ""
starting_string_2: str = ""
i: int = 0
i_2: int = 0
truth: bool = True
if direction == "left":
while i < len(given):
if i > 0 and given[i] != " " and given[i-1] == " ":
ending_point: int = i
if i > ending_point:
starting_string += given[i]
return starting_string
if direction == "right":
while truth:
starting_point = i_2 + 1
starting_string_2 += given[i_2]
if given[i_2] != " " and given[starting_point] == " ":
truth = False
i_2 += 1
return starting_string_2

试图保留尽可能多的代码:

def strip(given: str, direction: str) -> str:
starting_string: str = ""
starting_string_2: str = ""
i: int = 0
i_2: int = 0
truth: bool = True
ending_point = len(given)  # need to set this
if direction == "left":
while i < len(given):
if i > 0 and given[i] != " " and given[i-1] == " ":
ending_point: int = i
# following line must shifted left to match previous if
if i >= ending_point:  # use >=, not >
starting_string += given[i]
i+=1   #  increment counter else infinite loop
return starting_string
if direction == "right":
while truth:
starting_point = i_2 + 1
starting_string_2 += given[i_2]
if given[i_2] != " " and given[starting_point] == " ":
truth = False
i_2 += 1
return starting_string_2

s = '    hello    '
print('>' + strip(s,'left') + '<')
print('>' + strip(s,'right') + '<')
print('>' + strip(strip(s,'right'),'left') + '<')

输出

>hello    <
>    hello<
>hello<

使用重新拆分

import re
def fun(str_, cond):
...     return {"left": re.split(r"^s+",cond)[1], "right": re.split(r"s+$",str_)[0]}.get(cond, "Cond should be left or right")

最新更新