How can I replace some integers to strings? - python

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

Related

Slicing a dictionary's value isn't working properly

So I have a json file which contains role ids (a dictionary named roles),with a key (which is the name of the role) and each key has the role's id as it's value
Looks something like this:
{"Ban": ["694175790639743076"], "Muted": ["692863646543380590"]}
I mostly just need the ids from the json
using something like roles['Muted'] or roles.get('Muted') gives me ['692863646543380590']:
Muted=roles.get('Muted')
print(Muted)
the functions take integers,so I have to remove [' from the output and get this: 692863646543380590
slicing just gives me [] no matter what slicing I use:
work=boost1[2:20] *or any other slice*
print(work)
gives out "[]"
why is slicing just not working here? and how do I fix this??
first of all roles['Muted'] is a list, if you want just first element then get it with 0 index then try using int() for converting it to Integer:
Muted=int(roles.get('Muted')[0]) # or Muted=int(roles['Muted'][0])
Muted will be:
692863646543380590
Try this -
work = int(boost1[0]) #fetching the first element of list and converting it into int

How to fix TypeError: can only concatenate str (not "list") to str

I am trying to learn python from the python crash course but this one task has stumped me and I can’t find an answer to it anywhere
The task is
Think of your favourite mode of transportation and make a list that stores several examples
Use your list to print a series of statements about these items
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
print("I like the "+cars[0]+" ...")
I’m assuming that this is because I have letters and numbers together, but I don’t know how to produce a result without an error and help would be gratefully received
The error I get is
TypeError: can only concatenate str (not "list") to str**
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', new_dinner)
use comma , instead of plus +
If you use plus sign + in print ('this is old friend' + new_dinner) statement you will get error.
Your first line actually produces a tuple of lists, hence cars[0] is a list.
If you print cars you'll see that it looks like this:
(['rav4'], ['td5'], ['yaris'], ['land rover tdi'])
Get rid of all the square brackets in between and you'll have a single list that you can index into.
This is one of the possibilities you can use to get the result needed.
It learns you to import, use the format method and store datatypes in variables and also how to convert different datatypes into the string datatype!
But the main thing you have to do is convert the list or your wished index into a string. By using str(----) function. But the problem is that you've created 4 lists, you should only have one!
from pprint import pprint
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
Word = str(cars[0])
pprint("I like the {0} ...".format(Word))
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', str(new_dinner))
#Try turning the list into a strang only
First, create a list (not tuple of lists) of strings and then you can access first element (string) of list.
cars = ['rav4', 'td5', 'yaris', 'land rover tdi']
print("I like the "+cars[0]+" ...")
The above code outputs: I like the rav4 ...
You can do like
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', *new_dinner)
Here you are the answer :
cars = (['rav4'], ['td5'], ['yaris'], ['land rover tdi'])
print("I like the "+cars[0][0]+" ...")
What we have done here is calling the list first and then calling the first item in the list.
since you are storing your data in a tuple, this is your solution.

work with image: imgcompare does not support list?

import imgcompare
...
for filename in os.listdir(myPath):
if filename.endswith(".png"):
listIm1.append(filename)
for filename2 in os.listdir(myPath2):
if filename2.endswith(".png"):
listIm2.append(filename2)
so i fill my two lists with images,now I would like to compare the images of the two lists one by one following the same index, for example:listIm1[0] with listImg2[0]listIm1[1] with listImg2[1]and so on... and that's the code:
for item in listIm1:
ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
print ifSame
but get the error:
same = imgcompare.is_equal(listIm1[item], listIm2[item], tolerance=2)
TypeError: list indices must be integers, not str
it seems that imgcompare.is_equal() does not work with lists, is there some pythonic expedient to make it
works?
since
if filename2.endswith(".png"):
listIm2.append(filename2)
for item in listIm1:
# item = "someimagine.png"
ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
#listIm1[someimagine.png] is what you are asking => retrun Type Error
I guess you are looking for something like this:
edit:
import os
for filename in os.listdir(myPath):
if filename2.endswith(".png"):
img_path = os.path.join(myPath,filename2)
listIm2.append(img_path)
listIm1 = []
listIm2 = []
for i in range(len(listIm1)):
ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)
print ifSame
and it's better if len(listIm1) == len(listIm2)
The problem here is that you are trying to get the index of listIm1 by using item. What you want to do is use a range(), like:
for i in range(len(listIm1)):
ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)
As #Matt pointed out, this will only work if you know the lists are the same length beforehand, otherwise it will throw an index error.
You are using a for each loop, which grabs each element in your provided list listIm1 and stores it in a temp variable item, you then pass item (which is a string) as an index both of your lists. Indices of a list must be an integer, and that is the error you are getting.
for dir1_file in listIm1:
for dir2_file in listIm2:
ifSame = imgcompare.is_equal(dir1_file,dir2_file,tolerance=2)
print ifSame
This code uses two for each loops, it looks at each element in both of the lists and uses them as the arguments for your method.

This code keeps giving me: string indices must be integers

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]

TypeError: tuple indices must be integers or slices, not str

I need to make a function that updates tuples in a list of tuples. The tuples contain transactions, which are characterised by ammount, day, and type. I made this function that should completely replace a tuple with a new one, but when I try to print the updated list of tuples I get the error:
TypeError: tuple indices must be integers or slices, not str
The code:
def addtransaction(transactions, ammount, day, type):
newtransactions = {
"Ammount": ammount,
"Day": day,
"Type": type
}
transactions.append(newtransaction)
def show_addtransaction(transactions):
Ammount = float(input("Ammount: "))
Day = input("Day: ")
Type = input("Type: ")
addtransaction(transactions, ammount, day, type)
def show_all_transaction(transactions):
print()
for i, transaction in enumerate(transactions):
print("{0}. Transaction with the ammount of {1} on day {2} of type: {3}".format(
i + 1,
transaction['Ammount'], ; Here is where the error occurs.
transaction['Day'],
transaction['Type']))
def update_transaction(transactions): ; "transactions" is the list of tuples
x = input("Pick a transaction by index:")
a = float(input("Choose a new ammount:"))
b = input("Choose a new day:")
c = input("Choose a new type:")
i = x
transactions[int(i)] = (a, b, c)
addtransaction(transactions, 1, 2, service)
show_all_transaction(transactions)
update_transaction(transactions)
show_all_transaction(transactions)
A tuple is basically only a list, with the difference that in a tuple you cannot overwrite a value in it without creating a new tuple.
This means you can only access each value by an index starting at 0, like transactions[0][0].
But as it appears you should actually use a dict in the first place. So you need to rewrite update_transaction to actually create a dict similar to how addtransaction works. But instead of adding the new transaction to the end you just need to overwrite the transaction at the given index.
This is what update_transaction already does, but it overwrites it with a tuple and not a dict. And when you print it out, it cannot handle that and causes this error.
Original answer (Before I knew the other functions)
If you want to use strings as indexes you need to use a dict. Alternatively you can use namedtuple which are like tuples but it also has an attribute for each value with the name you defined before. So in your case it would be something like:
from collections import namedtuple
Transaction = namedtuple("Transaction", "amount day type")
The names given by the string used to create Transaction and separated by spaces or commas (or both). You can create transactions by simply calling that new object. And accessing either by index or name.
new_transaction = Transaction(the_amount, the_day, the_type)
print(new_transaction[0])
print(new_transaction.amount)
Please note that doing new_transaction["amount"] will still not work.
This is not a generic answer, I'll just mention it if someone bumps into the same problem.
As stated before, tuples are addressed by integer e.g. my_tuple[int] or slice my_tuple[int1:int2].
I ran into trouble when I ported code from Python2 to Python3. The original code used somthing like my_tuple[int1/int2], this worked in Python2 since division int/int results in int.
in Python3 int/int results in a floating point number.
I had to fix the code to my_tuple[int1//int2] to get the python2 behavior.

Categories

Resources