how can I change string character where I had known index? [closed] - python

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)

Related

Replace function, how to assign "b" multiple values? [closed]

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.

How do I convert a list of strings to integers in Python [closed]

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.

creating List within a list in recurrsion from string python [closed]

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", "]")

shortest repeated substring [PYTHON] [closed]

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 6 years ago.
Improve this question
Is there a quick method to find the shortest repeated substring and how many times it occurs? If there is non you only need to return the actual string ( last case ).
>>> repeated('CTCTCTCTCTCTCTCTCTCTCTCT')
('CT', 12)
>>> repeated('GATCGATCGATCGATC')
('GATC', 4)
>>> repeated('GATCGATCGATCGATCG')
('GATCGATCGATCGATCG', 1)
Because some people think it's 'homework' I can show my efforts:
def repeated(sequentie):
string = ''
for i in sequentie:
if i not in string:
string += i
items = sequentie.count(string)
if items * len(string) == len(sequentie):
return (string, items)
else:
return (sequentie, 1)
Your method unfortunately won't work, since it assumes that the repeating substring will have unique characters. This may not be the case:
abaabaabaabaabaaba
You were somewhat on the right track, though. The shortest way that I can think of is to just try and check over and over if some prefix indeed makes up the entire string:
def find_shorted_substring(s):
for i in range(1, len(s) + 1):
substring = s[:i]
repeats = len(s) // len(substring)
if substring * repeats == s:
return (substring, repeats)
It's not very efficient, but it works. There are better ways of doing it.

Finding if letter = another letter in python [duplicate]

This question already has answers here:
invalid syntax on =? [closed]
(2 answers)
Closed 8 years ago.
This is in python and I'm having a little trouble finding this out, I put.
s = 'goodbye'
and I want to know if the first letter is a g.
so i put
s[0] = 'g'
but i get an error, what is the right way to finding this?
A single = means 'assignment', and doing two == means 'compare and see if they're equal'. The difference between the two can be subtle (just a single character difference!), so make sure you don't get confused between the two
You want s[0] == 'g':
if s[0] == 'g':
print "word starts with 'g'"
Doing s[0] = 'g' is telling Python "change the first letter of the string to 'g'". However, that fails because in Python, strings are immutable -- they can never be changed.
You could use the startswith(prefix) method (returns True if string starts with the prefix, otherwise returns False):
>>> s = 'hello'
>>> a = s.startswith('h')
>>> a
True

Categories