在Python中,如何在给定字符串的左侧和右侧使用任何前导空格生成新字符串?
基于第二个参数,在字符串的右侧或在字符串的右侧尝试空格。 我们不允许使用lstrip/rstrip或任何内置字符串方法 我把右边弄下来了,但我在和左边搏斗。我的代码怎么了在Python中,如何在给定字符串的左侧和右侧使用任何前导空格生成新字符串?,python,Python,基于第二个参数,在字符串的右侧或在字符串的右侧尝试空格。 我们不允许使用lstrip/rstrip或任何内置字符串方法 我把右边弄下来了,但我在和左边搏斗。我的代码怎么了 def strip(given: str, direction: str) -> str: starting_string: str = "" starting_string_2: str = "" i: int = 0 i_2: int = 0
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条带(给定:str,方向:str)->str:
起始字符串:str=“”
正在启动\u字符串\u 2:str=“”
i:int=0
i_2:int=0
真相:bool=True
如果方向==“左”:
而我0并给定[i]!=“”并且给定[i-1]=“”:
终点:int=i
如果i>结束点:
起始字符串+=给定的[i]
返回起始字符串
如果方向==“右”:
而事实是:
起点=i_2+1
起始字符串\u 2+=给定[i\u 2]
如果给出[i_2]!=“”并给定[起点]=“”:
真=假
i_2+=1
返回起始字符串2
使用重新拆分
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")
尝试保留尽可能多的代码:
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') + '<')
def条带(给定:str,方向:str)->str:
起始字符串:str=“”
正在启动\u字符串\u 2:str=“”
i:int=0
i_2:int=0
真相:bool=True
结束点=len(给定)#需要设置此值
如果方向==“左”:
而我0并给定[i]!=“”并且给定[i-1]=“”:
终点:int=i
#以下行必须左移以匹配上一个if
如果i>=结束点:#使用>=,而不是>
起始字符串+=给定的[i]
i+=1#增量计数器else无限循环
返回起始字符串
如果方向==“右”:
而事实是:
起点=i_2+1
起始字符串\u 2+=给定[i\u 2]
如果给出[i_2]!=“”并给定[起点]=“”:
真=假
i_2+=1
返回起始字符串2
s=‘你好’
打印('>'+条带,'left')+''+条带,'right')+''+条带,'right'),'left')+'我们不允许使用lstrip:(啊,对不起-我的意思是我们不允许使用strip或任何内置字符串方法。我只是很抱歉地读了一遍哇,非常感谢!如果你不介意的话,你能简单解释一下你的更改吗?我做错了什么,为什么不起作用?非常感谢!
>hello <
> hello<
>hello<