How to reverse and manipulate a string in python [duplicate] - python

This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed last year.
I am creating a translator in python . This translator is going to change a normal text to a text with some special things :
At the first of each word we add "S"
At the End of each word we add "Di"
We reverse each word
example :
Hello Everyone --> SHello SEveryone --> SHelloDi SEveryoneDi --> iDolleHS iDenoyrevES
I did first two parts easily; but third part is a little tricky
my code :
n = input("Enter Text : ")
y = n.split()
z = 0
for i in y:
x = str("S" + i)
y[z] = x
z = z + 1
z = 0
for i in y:
x = str(i + "Di")
y[z] = x
z = z + 1
print(y)
z = 1
for i in y:
globals()["x%s" % z] = []
for j in i:
pass
In pass part I wanna to do something like this x{i}.append(j)
and then we reverse it.
How do I do this?

You can reverse it using ::-1, it means from start to beginning in reverse order:
For example:
print("abcd"[::-1]) # will prin dcba
So the code for every word can look like this:
result = "S"+word+"Di"
result = result[::-1]
Now you just have to put that in a loop and do it for every word.

Related

Use integer operator on string from index [duplicate]

This question already has answers here:
Changing one character in a string
(15 answers)
Closed 2 years ago.
In this code here
x = '123'
How can I addition let's say 5 to the second index. So x would be '173'.
x = '123'
n = 5
result = x[:1] + str(int(x[1]) + n) + x[2:]
print(result)
Prints:
173
For n=9:
1113
Split it into a list, try to turn them into ints or floats, and do your math.
x = "123"
x = list(x)
for i in range(0, len(x)):
try:
x[i] = int(x[i])
except:
x[i] = x[i]
x[1] += 5
print(x)
It returns [1.0, 7.0, 3.0].
Split the string into a list, modify the element at the desired index, then join the list back into a string.
x = '123'
i = 1
n = 5
y = list(x)
y[i] = str(int(y[i]) + n)
print(''.join(y)) # -> 173
Based on scvalex's answer on Changing one character in a string in Python

I'm trying to WAP to convert denary to binary without using list

I have already seen a couple of programs for this. Just wanted to know what's wrong with this logic. It keeps on returning 'str' object does not support item assignment. I looked this up but still couldn't find a reason this occurs.I'm just a newbie so apologies in advance if I'm just overthinking things.
x = dec
a = 5
n = 1
remainder = str()
binary = str()
while a != 1:
a = x // 2
b = x % 2
x = a
z = str(b)
remainder = str(remainder + z)
if a == 1:
b = 1
z = str(b)
remainder = str(remainder + z)
print(remainder)
asd = len(remainder)
for y in range(1, asd + 1):
binary[y:y + 1] = remainder[-y:-y - 1]
print("It's binary form is ", binary)
The problem is here:
for y in range(1, asd + 1):
binary[y:y + 1] = remainder[-y:-y - 1]
# ^^^^^^^^^^^^^ error
What do you expect this to do? Python strings are immutable: you cannot assign to a string slice. You can only use the value (right-hand side of an assignment, for example), or replace the variable's entire value.
I suspect that you're trying to reverse the string. Do it like this:
rev = remainder[::-1] # Whole string, but in reverse order

convert hexstring to individual bytes python 2.7

Morning all,
This is probably super easy but my brain just isn't working today.
So I have a string of hex f70307d600017010 I need to convert it to \xf7\x03\x07\xd6\x00\x01\x70\x10
or something to that effect, i.e escaping the string to hex.
Anyone have any suggestions?
Thanks
Jim
If you want the result of that output as a literal, i.e.:
>>> '\xf7\x03\x07\xd6\x00\x01\x70\x10'
'\xf7\x03\x07\xd6\x00\x01p\x10'
Use the binascii module:
>>> import binascii
>>> s = "f70307d600017010"
>>> binascii.unhexlify(s)
'\xf7\x03\x07\xd6\x00\x01p\x10'
This is by no means the way you should be doing it, but considering I'm bored:
x = "f70307d600017010"
y = "\\"
count = 1
for letter in x:
print(count)
if count > 2:
y = y + "\\" + "x" + letter
count = 1
elif 1 == count:
y = y + "x" + letter
elif count % 2 == 1:
y = y + letter + "\\"
elif count % 2 == 0:
y = y + letter
count = count + 1
There are several solutions to this using regular expressions. My favorite is this:
re.sub('(..)', r'\x\1', 'f70307d600017010')
Another could be:
''.join(r'\x' + x for x in re.findall('..', 'f70307d600017010'))
These will create a string of escaped bytes (based on the assumption that the tag "escaping" was meaning this). If you instead want to create a string of unescaped bytes:
re.sub('(..)', lambda m: chr(int(m.group(), 16)), 'f70307d600017010')
EDIT: I now prefer the answer of #juanpa-arrivillaga using the binascii module: binascii.unhexlify('f70307d600017010')

How do I get the rows to columns to be the row and vice versa [duplicate]

This question already has answers here:
Transpose list of lists
(14 answers)
Closed 5 years ago.
Here is some code I wrote
def binomial_coefficient(x,y):
if y == x:
div = 1
elif y == 1:
div = x
elif y > x:
div = 0
else:
a = math.factorial(x)
b = math.factorial(y)
c = math.factorial(x-y)
div = a // (b * c)
return(div)
def problem_9():
for k in range(6):
empty = '\t'
for zed in range(1,6):
X_sub = (10*zed,(1/5)*zed)
n = X_sub[0]
P = X_sub[1]
formula = binomial_coefficient(n,k)*(P**k)*(1-P)**(n-k)
empty = empty + str(formula) + '\t'
print(empty)
problem_9()
I have the code giving me the correct mathematical values but I need the first column to switch places with the first row. I would like the same thing to happen for each subsequent iteration of the loops. Can anyone help?
just permute the indices :
for zed in range(1,6):
empty = '\t'
for k in range(6):

What am I doing wrong? Adding 1 to use input

Having some difficulty with this problem. The program should get a number from the user. It will be the amount of triangles. The first triangle should have two rows. Each new triangle will have one extra row than the last triangle.
This is what I have:
numTri = input('Please umber of triangles: ')
numTri = eval(numTri)
numRow = 2
x = 0
while j<numTri:
y = '*'
z = 0
while z<numRow:
print y
y = y + *
z += 1
x += 1
numRow += 1
Getting an invalid syntax error on the print line. Not sure if I'm doing anything else wrong. Anyone have any idea?
Assuming you are using Python 3, there is a lot of errors in your code. Let us see them:
Major problems
The j variable
You use a j variable, in the loop condition, which is not set neither used anywhere. This will result in an error:
while j<numTri:
I believe you want to use the x variable:
while x<numTri:
print() is a function
In Python 3, you should put the parameters of a print() function between parenthesis, which is not the case:
print y
Too easy to solve:
print(y)
Note that the parenthesis are optional in Python 2.
'*' char without quotes:
You try to append the '*' char to the string from y but does not enclose the char with quotes:
y = y + *
The interpreter will see this asterisk as the multiplication operator, which will yield an error. Just enclose it with quotes (single or double, it does not matter):
y = y + '*'
Indentation problem
A specially pernicious problem in your code is that, after the second while loop, your code does not return to the same indentation level of the loop. I replaced the spaces below with open boxes so we can count them:
␣␣␣while z<numRow:
␣␣␣␣␣␣␣␣␣print y
␣␣␣␣␣␣␣␣␣y = y + *
␣␣␣␣␣␣␣␣␣z += 1
␣␣␣␣x += 1
␣␣␣␣numRow += 1
Alas, there is one more space in the two last lines when compared with the while line. You should remove those spurious spaces.
A resulting code will be:
numTri = input('Please umber of triangles: ')
numTri = eval(numTri)
numRow = 2
x = 0
while x<numTri:
y = '*'
z = 0
while z<numRow:
print(y)
y = y + '*'
z += 1
x += 1
numRow += 1
Minor problems
There are also some other details in your code which would be considered bad practices. Those will not matter a lot to you yet, since you are really novice, but we can explore some of them.
Avoiding eval()
eval() is a powerful yet risky function, so we avoid using it. It is specially easy to do in your case, since int() will convert the read string to an integer without problems:
numTri = input('Please umber of triangles: ')
numTri = int(numTri)
Non-standard indentation
Sometimes, you indent what is inside your loops with four spaces:
␣␣␣y = '*'
␣␣␣z = 0
␣␣␣while z<numRow:
then with six spaces
␣␣␣␣␣␣print(y)
␣␣␣␣␣␣y = y + '*'
␣␣␣␣␣␣z += 1
and even with four spaces, which results in an error:
␣␣␣␣x += 1
␣␣␣␣numRow += 1
The best thing to do is to always use the same indentation size. PEP 8 (a set of recommendations for all Python programmers) recommends to use four spaces for each indentation:
␣␣␣␣y = '*'
␣␣␣␣z = 0
␣␣␣␣while z<numRow:
␣␣␣␣print(y)
␣␣␣␣y = y + '*'
␣␣␣␣z += 1
␣␣␣␣x += 1
␣␣␣␣numRow += 1
while instead of for
This one is hard stuff for novices, but it may be helpful to point nonetheless. Your code would be much better if you used for loops with the range() function:
for x in range(0, numTri+1):
y = '*'
for z in range(0, numRow+1):
print(y)
y = y + '*'
numRow += 1
However, as you are a student, I believe you will learn about this feature some time in the future, so take it easy :)
The resulting code:
numTri = input('Please umber of triangles: ')
numTri = int(numTri)
numRow = 2
for x in range(0, numTri+1):
y = '*'
for z in range(0, numRow+1):
print(y)
y = y + '*'
numRow += 1
j is never defined before you reach the while loop. Maybe you meant while x < numTri: instead?
Also, the
x = 0
while x < numTri:
# do something
x += 1
construct is not very Pythonic; try
for x in range(numTri):
# do something
instead.
But I think the syntax error (and thus answering your question) is because you are using Python 3 where print needs round brackets. So :
print ( y )
And if you just want the highest grade for your programming task:
print('\n'.join('*'*y for x in range(int(input('Please umber of triangles: '))) for y in range(1,x+3)))
numTri = int(raw_input('Please umber of triangles: '))
or on python 3.x
numTri = int(input('Please umber of triangles: '))

Categories

Resources