Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
My problem is very small, and is that I can't do a normal letter substitution. I know the .replace command, but I can't seem to use it correctly.
For example: My k##yb0%%rd is br###k##n. ### should be replaced with o, ## with e, and %% with a. Thanks!
a = input("What did she say? ")
b = a.replace("###", "o")
print(b)
You can try something like this:
a = input("What did she say? ")
d = {'###':'o', '##':'e','%%':'a'}
for k,v in d.items():
a = a.replace(k, v)
b = a # if you need value in b variable
print(b)
You can create such dictionary and use it replace multiple values. Make sure to properly arrange your dictionary.
As the first thing I would suggest to read the Python's documentation for str.replace.
I would suggest something like this:
b = a.replace("###", 'o').replace("##", 'e').replace("%%", 'a')
This is possible because the returned value of a.replace("###", 'o') is of type str, so that the method replace can be applied on it too.
If you don't know which characters will be replaced, you should do like suggested by Vaibhav, creating a dict that associates old chars (key) with new chars (value).
What's more str is an immutable type, so you can't just do
a.replace("###", 'o').replace("##", 'e').replace("%%", 'a')
but anyway you don't have to assign the returned value to b, you can't reassign it to a without problems:
a = a.replace("###", 'o').replace("##", 'e').replace("%%", 'a')
and you can print it directly too.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
need to convert this list :
a = ["['0221', '02194', '02211']"]
type = list
to this list :
a = ['0221', '02194', '02211']
type = list
If your new to python this code would seem like very complicated, but i will explain whats in this piece of code:
a=["['0221', '02194', '02211']"]
a1=[]
nums_str=""
for i in a:
for j in i:
try:
if j=="," or j=="]":
a1.append(nums_str)
nums_str=""
nums=int(j)
nums_str+=str(nums)
except Exception as e:
pass
else:
a=a1.copy()
print(a)
print(type(a))
Steps:
Used for loop to read the content in list a.
Then again used a for loop to read each character in the string of i.
Then used try to try if i can typecast j into int so that it would only add the numbers to nums_str.
Then appended the nums_str to the list a1 if j if = "," or "]".
Continued the above process on each item in a.
After the for loop gets over, i change a to copy of a1.
You can use astliteral_eval to convert strings to Python data structures. In this case, we want to convert the first element in the list a to a list.
import ast
a = ast.literal_eval(a[0])
print(a)
# ['0221', '02194', '02211']
Note: Python built-in function eval also works but it's considered unsafe on arbitray strings. With eval:
a = eval(a[0]) # same desired output
You can try list comprehension:
a = a[0][2:][:-2].split("', '")
output:
a = ['0221', '02194', '02211']
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need help on how to convert a list to integers, for example
lst = ["1", "2", "3"]
Desired output:
123
I think I explain myself, I do not speak English so I use a translator, I hope it is understood.
You need to do two things: 1. concatenate the elements of the array together into a single string, and 2. convert that string to a number.
You can do #1 with the join string method. Normally, you call join on some other string that you want to put in between the ones you're joining, but since you don't want one of those here, you can just use the empty string:
>>> lst=["1","2","3"]
>>> "".join(lst)
'123'
Since that's still a string, not a numeric value, this is where step 2 comes in. You can convert it to an integer with the int function:
>>> int("".join(lst))
123
Join the strings, then convert to an integer:
int(''.join(lst))
The alternative of converting to integer and then joining is much more complicated, and will drop any leading zeros you have:
from math import floor, log10
result = 0
for x in lst:
n = int(x)
result *= 10**((x and floor(log10(x))) + 1)
result += n
Because of how Python's and operator works, the expression x and ... returns x immediately if it is zero, and the right hand side if not, which is what you want when taking logarithms.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to use a list of values to alter a bunch of class values that I added to another (temporary) list.
class game_events():
def __init__(self):
self.stage = 0
self.rules = False
saved_vars = [12, True]
game = game_events()
i = 0
for x in [game.stage, game.rules]:
x = saved_vars[i]
i+=1
It seems like everything is working, but that only the temporary list is being altered, like a decoy.
Desired results:
game.stage == 12
game.rules is True
Actual results:
game.stage == 0
game.rules is False
Any ideas?
When you do x = saved_vars[i], you're rebinding the variable x, not modifying the game object where it's previous value came from. If you want to modify just a few attributes on game, it's a whole lot easier to just do so directly:
game.stage, game.rules = saved_vars[0:2]
If you have a whole lot of attributes to go through, rather than just two in this example, you might return to your loop idea, but you'd need to do it differently. Rather than an assignment, you'd need to use setattr. And that means you'll need to specify the name of the attributes as strings, not with dotted notation:
for attr, value in zip(['stage', 'rules'], saved_vars):
setattr(game, attr, value)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
in Python,I have a string like "MARINE" and I must change A to M and M to A. I know A[1] is "A" and A[0] is "M" but I can't A[0] = A[1] (overwriting isn't allowed) so I think I can use replace but I failed .What can I do ?
Use a translation table.
>>> table = str.maketrans("AM", "MA")
>>> "MARINE".translate(table)
"AMRINE"
maketrans is a convenience function for creating a table where most characters are mapped to themselves. Here, we're mapping A to M, M to A, and leaving everything else alone. The translate method uses this table to replace each character in the str object using the character specified by the given table.
Documentation for both str.maketrans and str.translate can be found in the Python documentation. maketrans, in particular, provides several ways to build a translation table.
If the variable you used to store your strin is called A then this would work.
A.replace("MA", "AM")
You can use traditional for loop
s = "MARINE"
new_s = ""
for i in s:
if i == "M":
new_s = new_s + "A"
elif i == "A":
new_s = new_s + "M"
else:
new_s = new_s + i
print(new_s)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to create a list from a string
input string
st = "zzabcxzghfxx"
the list is enclosed in 'z' and 'x'
this is my attempt to create a recursive function
st = "zzabcxzghfxx"
def createlist(strin):
l1=[]
for i in st:
if(i=='x'):
createlist(strin)
elif(i=='z'):
l1.append(i)
return(l1)
following is the desired output:"[[abc][ghf]]"
string = "zzabcxzghzfxx"=> [[abc][ghzf]]"
Using regex.
Ex:
import re
st = "zzabcxzghfxx"
print(re.findall(r"z+(.*?)(?=x)", st))
#or print([[i] for i in re.findall(r"z+(.*?)(?=x)", st)])
Output:
['abc', 'ghf']
You could strip the trailing x and z and split on xz:
st.strip('xz').split('xz')
# ['abc', 'ghf']
Does it have to be recursive? Here's a solution using itertools.groupby.
from itertools import groupby
string = "zzabcxzghfxx"
def is_good_char(char):
return char not in "zx"
lists = [["".join(char for char in list(group))] for key, group in groupby(string, key=is_good_char) if key]
print(lists)
Output:
[['abc'], ['ghf']]
EDIT - Just realized that this might not actually produce the desired behavior. You said:
[a] list is enclosed in 'z' and 'x'
Which means a sublist starts with 'z' and must end with 'x', yes? In that case the itertools.groupby solution I posted will not work exactly. The way it's written now it will generate a new sublist that starts and ends with either 'z' or 'x'. Let me know if this really matters or not.
st.replace("z", "[").replace("x", "]")