【问题标题】:Find and string getting - string indices must be integers查找和字符串获取 - 字符串索引必须是整数
【发布时间】:2018-03-22 23:33:35
【问题描述】:

谁能告诉我这段代码有什么问题。我不断得到字符串索引必须是整数,我已经尝试了我能想到的一切。它实际上是在一个 if 语句中,但我将它剥离到这个,看看我是否能找到问题。 Find 为我正在搜索的字符串返回 23。我添加了 int 函数,看看是否可以修复它。

stringloc = 1
stringloc = text.find('http')
print(stringloc)
print(text[0, int(stringloc)])

这是返回信息 打印(文本[0,int(stringloc)]) TypeError: 字符串索引必须是整数

【问题讨论】:

  • 你知道text[0, int(stringloc)]在做什么吗?也许你想要text[:int(stringloc)]
  • 我希望它从第一个字符开始并搜索直到 http 在字符串中。我有一个字符串。我想搜索一个子字符串,但只能在字符串中搜索到 http
  • 所以,你想要text[:int(stringloc)]
  • 抱歉,不知道是怎么复制的
  • 我想我不确定你的代码行是做什么的。对python很陌生

标签: python


【解决方案1】:

你可能想要使用这样的索引 [start:end]

In [1]: text="this is the text for demo"

In [2]: stringloc=text.find('text')

In [3]: stringloc
Out[3]: 12

In [4]: print(text[0:stringloc])
this is the 

在[5]中:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-06
    • 2020-08-09
    • 2020-08-28
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多