python - 打印或返回括号之间的字符串

标签 python

我正在尝试以与开始类似的方式编写一个函数,这样我就能明白它在做什么。我假设这可以用一行代码和一些奇特的函数来完成,但为了练习和理解,我试图提出类似的解决方案。

任务如下:函数在遇到方括号 [ 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/

相关文章:

python - 处理生成器中抛出的异常

python - 如何使用保存的模型在 google colab 中恢复训练?

python - 基于socket的简单python聊天程序

python - 使用 Django-openid-auth

Python 与子字符串的交集

python - 为什么在 except 子句中使用 `or` 不会导致 SyntaxError?它有有效的用途吗?

python - Pyenv 在升级到 Big Sur 后崩溃了

python - python opencv cam = cv2.VideoCapture(cn)

python - 如何在 .csv 文件中转义字符串 Python 2.7 中的逗号

python - 更改列表中的每第 n 个项目