I wanted to try to make a simple game to play in my terminal and I am stuck on this problem.
I have tried
l[y][x] = l[y][x].replace(' ','2')
And
l[y][x] = '2'
And all of these returns a type error
'str' object does not support item assignment.
how do I solve the problem above?
Edit:
l contains
['111111111',
'120000001',
'100000001',
'100000001',
'111111111'
]
You need to convert your list l into characters - what you have is a list of string elements.
#convert elements into characters
m = [list(x) for x in l]
print(m)
print(m[1][2])
m[1][2] = m[1][2].replace('0', '9')
print(m[1][2])
Related
Suppose the following list:
l = ['1','2','M']
How can I transform l to l_1 via a list comprehension?
l_1 = [1, 2, 'M']
I attempted the below without success.
[eval(c) if eval(c) not NameError else c for c in l]
File "<ipython-input-241-7c3f63ffe51b>", line 1
[eval(c) if c not NameError else c for c in list(a)]
^
SyntaxError: invalid syntax
Hi,
You could validate each element of the list l as strings, even if you already have some digits on it such as l = ['1','2','M',3,'p'], that way you have that validation there by passing them all to string and then verifying if the element is digit, and if so, you pass it to int, of float, or number to the new l_1 and if it is not, you simply pass it as string. In this case I will convert each numeric element to int, but you could choose to pass it to number in any other type such as float, for example, if the list contains floating elements.
l = ['1','2','M',3,'p']
l_1 = [int(el) if str(el).isdigit() else el for el in l]
print(l_1)
I certainly hope this helps, good luck and keep coding, it's always fun!
Assuming your general case looks like this, you could use isdigit to only convert numbers.
l=['1','2','M']
l1=[int(c) if c.isdigit() else c for c in l]
Would like my output which should not be string but my code returning string to me. Please look on my below code in which z is my output. I tried with regex, replace, strip, eval, ast.literal_eval but nothing worked for me as of now.
x = "'yyyymm'='202005','run_id'='51',drop_columns=run_id"
y = x.split(',')
print(y)
This will print:
["'yyyymm'='202005'","'run_id'='51'","drop_columns=run_id"]`
But I want:
['yyyymm'='202005','run_id'='51',drop_columns=run_id]
x is a string and if you split a string, you will get an array of strings. It is basically cutting it into pieces.
Your question is not really clear on what you want to achieve. If you want to have key-value-pairs, you'd need to split each token at the =. This would give you something like this:
[('yyyymm', '202005'), ('run_id', '51'), ('drop_columns', 'run_id')]
But the items in the tuples would still be strings. If you want to have integers, you would need to cast them which is only possible if the strings consist of digits. It would not be possible to cast 'run_id' to integer.
You can refer to this example. I'm not sure if that is 100% what you are looking for, but it should give you the correct idea.
x = "yyyymm=202005,run_id=51,drop_columns=run_id"
y = x.split(',')
tmp = []
for e in y:
tmp.append((e.split('=')[0], e.split('=')[1]))
out = []
for e in tmp:
if str.isnumeric(e[1]):
out.append((e[0], int(e[1])))
else:
out.append(e)
print(out)
This will give you:
[('yyyymm', 202005), ('run_id', 51), ('drop_columns', 'run_id')]
I'm trying to change characters from x into upper or lower character depending whether they are in r or c. And the problem is that i can't get all the changed characters into one string.
import unittest
def fun_exercise_6(x):
y = []
r = 'abcdefghijkl'
c = 'mnopqrstuvwxz'
for i in range(len(x)):
if(x[i] in r):
y += x[i].lower()
elif(x[i] in c):
y += x[i].upper()
return y
class TestAssignment1(unittest.TestCase):
def test1_exercise_6(self):
self.assertTrue(fun_exercise_6("osso") == "OSSO")
def test2_exercise_6(self):
self.assertTrue(fun_exercise_6("goat") == "gOaT")
def test3_exercise_6(self):
self.assertTrue(fun_exercise_6("bag") == "bag")
def test4_exercise_6(self):
self.assertTrue(fun_exercise_6("boat") == "bOaT" )
if __name__ == '__main__':
unittest.main()
Using a list as you are using is probably the best approach while you are figuring out whether or not each character should be uppered or lowered. You can join your list using str's join method. In your case, you could have your return statement look like this:
return ''.join(y)
What this would do is join a collection of strings (your individual characters into one new string using the string you join on ('').
For example, ''.join(['a', 'b', 'c']) will turn into 'abc'
This is a much better solution than making y a string as strings are immutable data types. If you make y a string when you are constructing it, you would have to redefine and reallocate the ENTIRE string each time you appended a character. Using a list, as you are doing, and joining it at the end would allow you to accumulate the characters and then join them all at once, which is comparatively very efficient.
If you define y as an empty string y = "" instead of an empty list you will get y as one string. Since when you declare y = [] and add an item to the list, you add a string to a list of string not a character to a string.
You can't compare a list and a string.
"abc" == ["a", "b", "c'] # False
The initial value of y in the fun_exercise_6 function must be ""
I used this. But it is not applicable for all the cases.
def splitword(verb_list):
split = -((-len(verb_list))//2)
return verb_list[:split], verb_list[split:]
print(verb_list)
If you want to remove a specific word from each string in a list you can use the str.replace() method in a list comprehension:
l = ['බලනවා', 'නටනවා']
l = [s.replace('නවා', '') for s in l]
l would become:
['බල', 'නට']
I am trying to edit and fill the lists in A, B and C using the input function.
A = ['']
B = ['']
C = ['']
key = input()
key[0] = 'X'
But i get this error.
TypeError: 'str' object does not support item assignment
How can i use the input function to edit my list. Or you might have better way to do this?
Thank You!
The strings per se in Python are immutable (you can't modify its content) however what you can do is to store them in a char list and a list in python is a mutable object, hence you can modify the char list as you see fit.
key = input() # "hello"
new_key = list(key) # ['h','e','l','l','o']
new_key[0] = 'X' # ['X','e','l','l','o']
Python strings are immutable objects which means you cannot change an existing string. The best you can do is create a new string that is a variation on the original. For e.g :
newstring = 'newchar' + oldstring[1:]
In your case it would be something like:
key = input()
newkey = 'X' +key[1:]
Solved. instead of using lists, better use dictionary to fill the A, B or C.
var = {'A':' ', 'B':' ', 'C':' '}
var[input()] = 'X'
Thanks for all of your participation!