List Being Read as String Not Int Python
PYTHON Type ERROR: STRING INDICES MUST BE INTEGERS-SOLUTION
Tin one call some other person past typing their name in the dial pad? NO! Typing password in the countersign field to log in ?(although information technology might work sometimes). Or take revenge from a useless person by using one'south own precious fourth dimension and energy? All of the mentioned takes on issues are futile and a picayune flake imbecilic. But however we practice information technology. Cypher to worry about each chore requires slight patience and mutual sense. The trouble that we will discuss in the article is likewise.
SYNOPSIS:
First of all, permit usa understand what is an iterable object : An iterable is an object, which returns 1 of its members at a time, allowing it to be iterated over in for-loop. In Python, iterable objects are indexed or placed in the data structures such equally string or dictionary using numbers i.eastward. integer. When values at index are extracted using cord value (incorrect type of input) it raises mistake like this :
' TypeError: string indices must be integers. '
The following article will interpret whether when and how the error occurs and how to resolve the error by understanding the anatomy of certain data structures via different scenarios. Each problem instance will be understood in depth, the pregnant volition be interpreted and eventually will be solved.
THE Trouble:
When i starts coding or is a beginner, information technology is the almost annoying thing 1 has to become through equally a programmer. It seems like the world has come to an end and one might never principal the art of coding. One is almost on the verge of giving up only 1 should not forget the all-time programmers in the world were naive in the beginning, they started somewhere and went through all of the errors and technical issues to be at the pinnacle of in that location game. Then are you. I must not give up that fast. Allow u.s. clear some air and gear upwardly!
To brainstorm with, ane must know the anatomy of the problem in order to solve it. Here the problem nosotros have is surely arising because of incompatibility of the argument nosotros pass through our data construction. Let us sympathize how and when error tin ascent through a couple of illustrations.
Scenario 1:
Suppose we have a string as shown below. Since Python is dynamically typed language i.east. the blazon of variable is checked during the run-fourth dimension, nosotros need non to mention keywords like int, str or char before the variable used. We try to index a part of the string which is a style to refer an individual item within an iterable (cord) by its position. In Python, objects are zero-indexed i.e. the position count starts at goose egg. At present we want to access the letter 'due east' from the string, i may follow the given approach:
In [1]: string="typeerror"
In [2]: string['east']
Traceback (almost recent call last): File "<ipython-input-eight-1b9006e9beb0>", line 1, in <module>
string['due east'] TypeError: string indices must be integers
The error is self-explanatory merely Let united states of america read what the bulletin is trying to say. Python is an interpreted language which means it will stop compiling the program every bit soon as syntax errors exist and will not run unless the problem is solved. Now it might confuse us that error is at the second line, but it says line ane. In the environs I accept used that is Spyder part of a Python distribution, Anaconda, the first line is called line 0. Thus, at line i information technology displays type error which denotes that the value of the indices provided is of another type. Nosotros are trying to extract a value from string using string index instead of integer index. Look at the following infographic to sympathise what exactly a cord looks like and how the items are indexed in the iterable:
Scenario 2:
Another way to extract a role of text from cord is via slicing. Slicing is a technique of getting a subset of elements (i.e. a small list based on index value) of the iterable (list). Information technology has prominent applications in tasks like optimization, mistake analysis, debugging, menses control and many more. Let us walk through an case:
In [iii]: mystring="gratitude"
In [4]: mystring[0,5]
Traceback (most recent telephone call last): File "<ipython-input-13-7c2881597196>", line ane, in <module>
mystring[0,v] TypeError: cord indices must be integers
How come? Despite we have used integer indexes to slice the iterable, it shows the same fault of compatibility issue and to be honest, not a right explanation to the mistake nosotros have fabricated. We need to dig a litter deeper, thus we volition relieve the integer alphabetize in another string object and then look up the type of the same.
In [five]: excerpt=0,5
In [six]: blazon(extract)
Out[six]: tuple
Because information technology is a tuple which one of the built-in data types in Python other than List, Set and Dictionary, it did not show the output nosotros expected. The comma , in the cord is automatically evaluated equally tuple and makes the error misleading. Therefore, the error should have been something like this:
In [vii]: mystring[extract]
Traceback (most contempo call final): File "<ipython-input-16-308e1ed6160d>", line 1, in <module>mystring[extract] TypeError: string indices must be integers(not tuple)
To acquire more about data types of Python visit the post-obit link: Python information types .
Scenario iii:
Next data structure is dictionary, and it is slightly complex than a listing thus, we must know how the structure is:
Dictionary={
key1 : value1,
key2 : value2,
.
.
keyN : valueN,
}
The key could be any entity similar proper name, accost, gender, and phone while values are the attributes like Max for name. One primal can fifty-fifty have multiple values separated by commas and double or single-quoted.
Let united states of america create a dictionary called "phone_book" with keys 'Name', 'Mobile', and 'Address' notwithstanding, we will take a simpler dictionary for improve understanding.
In [viii]: phone_book={ "Name": "Jennifer Aniston",
"Phone": "1800",
"Accost": "Apt20" }
In order to iterate over all the values in the dictionary and print them all, we will use the post-obit lawmaking snippet, where one thousand is for all the keys residing in the dictionary:
In [9]: for k in phone_book: ...: print("Proper name:" + chiliad["Name"])
...: impress("Phone:" + g["Phone"])
...: print("Address:" + k["Address"]) Traceback (nigh contempo call concluding): File "<ipython-input-20-e5c1b8f425c3>", line two, in <module>
print("Name:" + k["Name"]) TypeError: cord indices must be integers
Sigh! The fault is present because we are trying to admission values using cord alphabetize instead of the integer index. However, that is not all what it is shown and will elucidate further in the solutions department.
THE SOLUTION:
Scenario one:
Since we were using string index, we got the type error because values are stored at an accost starting from 0 in both cord and lexicon. Now we will effort to index the string using the integer as that is the correct fashion to excerpt data.
In [10]: string[0]
Out[ten]: 't'
Voila! It displayed what we were looking for. Effort yourself to excerpt items at different locations of iterable by passing values from 0–8.Wondering why and how 8? As nosotros saw in the above infographic that it had nine messages and the numbering started from zero, the last one is 8. But what if the string is longer and we accept not much time to count each letter and space(aye, space counts) , 1 can do the following to get the size of the string:
In [eleven]: string1 = "Hullo in that location"
In [12]: len(string1)
Out[12]: 7
Scenario 2:
Since we were slicing the string using comma, we got the type error as Python evaluates commas , equally tuple thus we replace that with colon ':'. Follow the code below:
In [thirteen]: mystring[0:5]
Out[xiii]: 'grati'
Scenario three:
In dictionary we tried to admission the values using 'thou' and passing the keys to it, only the problem is that in the for loop as explained clearly below:
· m is a central,
· primal is 'Name' in the lexicon 'phone_book' and
· we pass 'Name' to 'Name' to get the value.
We cannot use string to access other string. Perplexed right? It is like opening a lock using a lock. The following code will make it clearer.
In [14]: for k in phone_book:
...: print(grand)
...:
Proper name
Phone
Address
Here, we tried to admission the key's value( dict[key:value] ) by passing the central proper noun itself just the method to practice it is by passing the alphabetize or position of the item in object like string and for dictionary the name of the lexicon is to exist mentioned to recollect them. Thus, the solution to this is that we must use the dictionary name instead of 'k' as the lexicon cardinal tin exist strings. Thus, follow the beneath method:
In [15]: phone_book={
...: "Proper name": "Jennifer Aniston",
...: "Telephone": "1800",
...: "Address": "Apt20",
...: } In [sixteen]: impress("Name:" + phone_book["Name"])
...: impress("Phone:" + phone_book["Phone"])
...: print("Address:" + phone_book["Address"]) Name:Jennifer Aniston
Phone:1800
Accost:Apt20
Our code ran successfully! Since, we diagnosed the cause of the trouble, it became clearer and easier to solve it. The wrong argument passed to search the available content in the iterable ( strings, dictionaries) raised the error. Following that nosotros made changes appropriately and therefore, were able to get the expected output i.e. the item/alphabet at the mentioned location of string and details of lexicon with primal and its value.
CONCLUSION:
The lesson learned is that:
· string indices must be integer ( string[0] ) and
· slicing is washed through colon ':' ( string[0:1] ) non commas ',' equally Python thinks it a tuple.
· Moreover, dictionary items must be accessed only using dictionary name Not a cardinal in the dictionary. There y'all become! Now y'all can solve this mistake and work similar a pro!
FOLLOW FOR More!
valentinodiany1971.blogspot.com
Source: https://medium.com/analytics-vidhya/python-type-error-string-indices-must-be-integers-solution-dc53df846b0f
0 Response to "List Being Read as String Not Int Python"
Post a Comment