I keep getting a TypeError: string indices must be integers. Not sure how to correct this.
def get_next_target(string):
start_str=string.find('<')
if start_str==-1:
return None,0
end_str=string.find('>',start_str)
next_start_str=string.find('<',end_str)
if next_start_str==-1:
return string[end_str+1:]
word=string[end_str+1,next_start_str]
return word,next_start_str
print (get_next_target('<h1>Title <>'))
You are trying to use a , for string slicing, which is causing this to become a tuple. You need to replace the , with a :
word=string[end_str + 1:next_start_str]
Related
I started to learning today Python. I am trying to make a Fate dice bot for Discord. I want to replace an integer with a string and I wrote:
zarList = [1,-1,0]
zarsonuc = random.choices(zarList, k=4)
zarsonucsayi = sum(zarsonuc)
zartanim = {-4:'Felaket', -3:'Rezalet', -2:'Kötü', -1:'Dandik', 0:'Düz', 1:'Eh', 2:'İyi', 3:'Baya İyi', 4:'Harika'}
tanimsonuc = [zartanim.get(n,n) for n in zarsonucsayi]
await ctx.send(f"{tanimsonuc} bir zar attın.{sonuc},{zarsonucsayi}")`
But I take this TypeError :(
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not iterable.
Can anyone help me?
If you want to replace an integer to a string you can just cast it to a string. For example, if you want to cast the first number of your array to a string you may say:
str(zarList[0])
Hope it helps,(just answered by what you asked on the title)
Upon looking at your code, the error doesn't appear because the list elements are not a string but because you are trying to iterate over an int element and not an iterable object.
Here:
tanimsonuc = [tanim.get(n,n) for n in zarsonucsayi]
Since
zarsonucsayi = sum(zarsonuc)
returns an int value, and you can't iterate it.
You need to iterate using the range
tanimsonuc = [zartanim[n] for n in range(zar_sonuc_sayi)]
Output:
['Düz', 'Eh', 'İyi', 'Baya İyi']
Explanation
[zartanim.get(n,n) for n in zarsonucsayi]
You need to iterate through zarsonucsayi to do that use range(zarsonucsayi)
You wanted the value of the corresponding dice value, use zartanim[n]
zarList = [str(x) for x in zarList]
basicly you iterate trough the list and convert it to a string using str
I've created a list of characters named 'char' I thought this code would compare the user input but I am getting a TypeError
while True:
sorubir = input("Enter a character name: ")
for i in char:
if sorubir.upper() == char[i]:
print (sorubir)
else:
sorubir = input("Try again. Enter a character name: ")
for i in char already refers to the actual character in the array. I believe you thought i to be its index. That would be written instead as for i in range(0, len(char)), where i would take an index value.
In your current code, simply changing sorubir.upper() == char[i] to sorubir.upper() == i should do the trick!
Doing
for i in char:
Unless it's a list of numbers will return the data stored in that index.
For example you could be doing
char['foo']
That will return the type of error you were getting.
Instead try using
for i in range(len(char)):
This will return an integer for each index of the list.
I have a simple script that prints index of given character in a string. However when the string includes letters which are not English , I got error.
def toBinary(character):
binaryTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZÇÜŞĞİ"
return binaryTable.index(character)+1
But when use the binaryTable array , in a function , for example I permutate it using my own method
def permutation(text_block,permutation_array,reverse):
print permutation_array
temp = [None]*len(text_block)
temp_P = []
for i in permutation_array:
temp_P.append(i)
i = 0
if reverse:
#permutation_array.reverse()
temp_P.reverse()
for integer in temp_P:
temp [i] = text_block[integer]
i += 1
return temp,temp_P
the array includes ascii characters like "\xc4" , "\xb0" .So when I run my binary converter method after permutation method it calls like
toBinary("\xc4")
Therefore I get "TypeError: expected a string or other character buffer object" error in toBinary method.
How can I get rid of it?
I'm a complete amateur at python and programming. I'm trying to read a list of data from a JSON datafile on a server. It generates the following error:
TypeError: list indices must be integers, not str
I believe it goes back to this statement which needs some sort of change, but I don't know what it should be.
def grabDeviceIDs():
devices=[];
## parse the list
for deviceListJSON in (getDeviceListFromserver()['mobile_device_group']['mobile_devices']['mobile_device']):
d = Device()
d.id = deviceListJSON.get('id')
devices.append(d)
print "Found " + str(len(devices)) + " devices."
return devices
Any ideas?
You have one key too many; this should suffice:
for deviceListJSON in getDeviceListFromserver()['mobile_device_group']['mobile_devices']:
i got timestamp returned as a tuple from rrd database i.e. info variable will contain this
[(38177492.733055562,
38177482.886388876),(39370533.190833323, 40563588.018611118)]
inside my code i am converting tuple (38177492.733055562,38177482.886388876) intto list using
list function after that i am accessing element using "index" variable and when i am passing this value to fromtimestamp function it is asking me the "float" value so how can i convert list object into float primitive data type ? following is the whole code
def hello(request):
info = rrdtool.fetch('hello/test.rrd','AVERAGE','-r','3600','-s','1298264400','-e','1298350800')
datalist = list()
for index in range(0,len(info)):
val = list(info[index])
dt_obj = datetime.fromtimestamp(float(val[index]))
str=dt_obj.strftime("%d-%m-%Y %H:%M:%S")
datalist.append(str)
data = simplejson.dumps(info, indent=4)
return HttpResponse(data,mimetype='application/javascript')
i am getting following error
a float is required
after changing code to for index in range(0,len(info)): i am getting following error
invalid literal for float(): Out
What you're doing doesn't make much sense, I'm afraid - index is an index into the info list, not into val, which is one of the tuples in that list.
Also, you don't need to convert the list into a tuple in order to access an element of the tuple.
Your indentation is broken in the line where the loop starts, and also when you outdent to return a json version of info.
To work out your problem, you could start by printing val, val[index] and type(val[index]) on the line before your error to check that they are what you're expecting them to be - clearly they're not from the error you get.
Also, you don't need to use the index into the info list at all, you could iterate over the values in the list with:
for val in info:
# I'm not sure if you want both values in the tuple here or just one...
print >> sys.stderr, "val =", val
dt_obj = datetime.fromtimestamp(val[0])
str=dt_obj.strftime("%d-%m-%Y %H:%M:%S")
datalist.append(str)