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
Related
based on that code, I wish to output my result by ending each digit with a dot.
input:
x = 0
while x<=5:
print(x)
x += 1
expected output:
1.
2.
3.
4.
5.
Make sure you start at x = 1 and add a full stop to the string. Concatenating more letters or symbols to variables can be done with f-strings:
# Start at 1
x = 1
while x <= 5:
print(f'{x}.')
x += 1
Alternatively, you could turn this into a one liner function:
>>> def ordered(start, stop):
... return '\n'.join(f'{x}.' for x in range(start, stop+1))
...
>>> print(ordered(1, 5))
1.
2.
3.
4.
5.
Type casting can be used
x = 0
while x<=5:
print(str(x)+".")
x += 1
Just so you know, you can use the ` key to embed code :)
I believe what you want is:
x = 0
while x <= 5:
print(str(x) + '.')
x += 1
Let's break down the print statement:
We add the dot to x. We can't just add a string to an integer, so we first have to use the str() function to turn the numeric value of x into a string value: str(x) + '.'
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.
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
This question already has answers here:
How to split an integer into a list of digits?
(10 answers)
Closed 5 years ago.
for example i have this variable:
x=123
how can i convert it to a tuple or each digit into separate variables?:
x=(1,2,3)
or
x1=1
x2=2
x3=3
>>> x=123
>>> tuple(map(int, str(x)))
(1, 2, 3)
You can use a comprehension with a tuple after casting the value to a string:
x=123
x = tuple(int(i) for i in str(x))
Output:
(1, 2, 3)
Convert to a string, convert each digit to an int, then unpack directly into variables:
x = 123
x1, x2, x3 = [int(i) for i in str(x)]
This requires that you know in advance how many digits are present in the string. Better to just use a tuple or list to hold the digits and reference them by index.
t = tuple(int(i) for i in str(x))
t[0]
# 1
etc.
Code:
x = 1234567
digits = []
print("number: " + str(x))
while x > 0:
digits.append(x % 10)
x = int(x / 10)
# To put it back in order
digits.reverse()
for i in range(len(digits)):
print(digits[i])
Output:
number: 1234567
1
2
3
4
5
6
7
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):