我得到python错误TypeError:字符串索引必须是整数,而不是str

时间:2015-12-30 03:41:06

标签: python list python-2.7 dictionary

以下是我从JSON回复中获得的字典

text1 = [body["definitions"][0]["text"],
         body["definitions"][1]["text"]]

我正在尝试访问前两个文本'使用此代码语句:

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
 {
  private StaggeredGridLayoutManager staggeredGridLayoutManager;
  MyAdapter myAdapter;
  List<ItemData> grid_view_item = new ArrayList<>();
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);

 staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
 recyclerView.setLayoutManager(staggeredGridLayoutManager);
            //call the LoadImage
            new LoadImage().execute();
            myAdapter = new MyAdapter(MainActivity.this, grid_view_item);
            recyclerView.setAdapter(myAdapter);

       }

我得到了我需要的字符串。

但实际问题是,当我在覆盆子Pi 2上运行相同的代码时,我收到以下错误

  

TypeError:字符串索引必须是整数,而不是str

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

body["definitions"]返回一个字符串,说“你好”,所以如果你写:

body["definitions"]["0"]

相当于:

"hello"["0"]

产生错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

但如果你写:

"hello"[0]

你得到:

'h'