我正在尝试以与开始类似的方式编写一个函数,这样我就能明白它在做什么。我假设这可以用一行代码和一些奇特的函数来完成,但为了练习和理解,我试图提出类似的解决方案。
任务如下:函数在遇到方括号 [ word ] 时获取文本,它应该打印或返回方括号之间的所有单词。例如,如果文本字符串为“[a]n example[ string]”,则您应该打印出“a string”。
def string():
text = "some random text [and I need this bit of txt] but I don't know how to continue [to get this bit as well]"
for i in text:
for j in range(len(text)):
if text[j] == '[':
new = text.find(']')
return(text[j+1:new])
print(string())
最佳答案
试试这个:
def extract(text, skip_chars=("\n", )):
output = ""
flag = False
for c in text:
if c == "]":
flag = False
if flag and not c in skip_chars:
output += c
if c == "[":
flag = True
return output
print(extract("""[a]n example[
stri
ng]"""))
# -> "a string"
关于python - 打印或返回括号之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60213822/