首页 > 解决方案 > 如何/在何处在 Google docs API 中添加插入文本功能

问题描述

我从google api复制粘贴并在我的代码中使用令牌验证用户,然后立即执行此代码

text1="text"
text2="bruh"
text3="reee"
requests = [
     {
        'insertText': {
            'location': {
                'index': 25,
            },
            'text': text1
        }
    },
             {
        'insertText': {
            'location': {
                'index': 50,
            },
            'text': text2
        }
    },
             {
        'insertText': {
            'location': {
                'index': 75,
            },
            'text': text3
        }
    },
]

result = service.documents().batchUpdate(
    documentId=DOCUMENT_ID, body={'requests': requests}).execute()

但我不断收到一个错误代码,上面写着

    "Invalid requests[0].insertText: Index 25 must be less than the end index of the referenced segment, 2.

标签: pythongoogle-apigoogle-docs-api

解决方案


错误消息告诉您,您尝试插入文本的段只有两个字符长,并且您不能在索引 25 处插入任何内容,因为两个字符长的字符串只有索引 0 和 1。如果您更改索引为 0 或 1,它应该可以工作(至少对于第一个请求)。

文档中解释的开始和结束索引


推荐阅读