How to replace variable in string in a list [duplicate] - python

This question already has answers here:
Changing one character in a string
(15 answers)
Closed 2 years ago.
I have a list called x below and I want to replace the ">" (in x[0][0]) with the integer 1.
x = [">000#","#0#00","00#0#"]
I tried x[0][0] = 1 but it gives me an error.
Also, can I make x[0][2] to become an integer such that
x[0][2] += 1 becomes this:
x = ["1010#","#0#00","00#0#"]

You can try
x[0]=x[0].replace(">","1")
Strings are immutable so cant be changed like list.
Or you can convert to list.
x[0]=list(x[0])
x[0][0]="1"
x[0][2]=str(int(x[0][2])+1)
x[0]="".join(x[0])

Python strings are immutable; you cannot change their contents. Instead, you need to make a new string out of the old one and assign that to x[0]:
x = [">000#","#0#00","00#0#"]
# change the first character to a '1'
x[0] = '1' + x[0][1:]
# add 1 to the third character
x[0] = x[0][:2] + str(int(x[0][2]) + 1) + x[0][3:]
print(x)
Output:
['1010#', '#0#00', '00#0#']

Related

Why can't I manipulate inputted list (list = [input()]) ? If possible, how? [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 1 year ago.
I am creating a sequence identifier and I want a shorter code by manipulating the list. However:
#This is possible:
list = [1,2,3,4,5]
A = list[1] - list[0]
print(A)
#This is not possible:
list = [input()]
A = list[1] - list[0]
print(A)
[input()] is only one (string) element, so list[1] doesn't exist to be used in subtraction.
If you want a list of 5 user-entered integers, you would use
[int(input()) for _ in range(5)]
And press enter after each value
Or for space-separated values - [int(x) for x in input().split()]

Remove() function in loops and iterations python [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
vec = [-4,-2,0,2,4]
for x in vec:
if x<0:
print(x)
vec.remove(x)
print(vec)
This is a program to remove negative numbers and retain positive numbers in a list
Without the .remove(x), i printed out -4,-2
But with .remove(x),Why when I print(x), it prints out only -4, and only -4 is removed?
Isn't supposedly -2 will also be printed and removed? Isn't supposedly the vec list finally retains 0,2,4 ?
I have tried putting if x <0 or x==-2 , it doesn't work either instead returning me the same problems
I know I can build a new list like vectwo = [x for x in vec if x>0 or x=0]
but I just can't figured out the logical fallacy in the iteration I built to remove negative numbers.
Dont remove from the list while iterating. It's cleaner to use another list.
vec = [-4,-2,0,2,4]
vec_copy = []
for x in vec:
if x >= 0:
vec_copy.append(x)
print(vec_copy)
You can do this in a single line. But note that you aren't actually removing from numbers from the list, instead you pick the positive items and replace the old list with the new one. It does what you want and it's cleaner this way.
vec = [x for x in vec if x >= 0]

How to capitalize every other character in a string [duplicate]

This question already has answers here:
Capitalise every other letter in a string in Python? [closed]
(5 answers)
Closed 3 years ago.
I want the program to return ' mahir ' as 'MaHiR', I have got MHR but how do I get 'a' and 'h' at their usual place ?
I have already tried slicing but that does not work
s = 'mahir'
a = list (s)
c = a[0:5:2]
for i in range (len(c)):
print (c[i].capitalize(),end = " ")
Python's strings are immutable, calling c[i].capitalize() will not change c[i], and therefore will not change s, to modify a string you must create a new one out of it, you can use str.join with a generator expression instead:
s = 'mahir'
s = ''.join(c.upper() if i % 2 == 0 else c for i, c in enumerate(s))
print(s)
Output:
MaHiR
If you want to do it using slicing, you could convert your string to a list since lists are mutable (but the string approach above is better):
s = 'mahir'
l = list(s)
l[::2] = map(str.upper, l[::2])
s = ''.join(l)
print(s)
Output:
MaHiR

How to find maximum value of two numbers in python? [duplicate]

This question already has answers here:
How do I compare version numbers in Python?
(16 answers)
Closed 6 years ago.
I want to get the maximum value from a list.
List = ['1.23','1.8.1.1']
print max(List)
If I print this I'm getting 1.8.1.1 instead of 1.23.
What I am doing wrong?
The easiest way is, to use tuple comparison.
Say:
versions = ['1.23','1.8.1.1']
def getVersionTuple(v):
return tuple(map(int, v.strip().split('.')))
Now you can use, print(max(map(getVersionTuple, versions))) to get the maximum.
EDIT:
You can use '.'.join(map(str, m)) to get the original string (given m holds the max tuple).
These aren't numbers, they are strings, and as such they are sorted lexicographically. Since the character 8 comes after 2, 1.8.1.1 is returned as the maximum.
One way to solve this is to write your own comparing function which takes each part of the string as an int and compares them numerically:
def version_compare(a, b):
a_parts = a.split('.')
b_parts = b.split('.')
a_len = len(a_parts)
b_len = len(b_parts)
length = min(a_len, b_len)
# Compare the parts one by one
for i in range(length):
a_int = int(a_parts[i])
b_int = int(b_parts[i])
# And return on the first nonequl part
if a_int != b_int:
return a_int - b_int
# If we got here, the longest list is the "biggest"
return a_len - b_len
print sorted(['1.23','1.8.1.1'], cmp=version_compare, reverse=True)[0]
A similar approach - assuming these strings are version numbers - is to turn the version string to an integer list:
vsn_list=['1.23', '1.8.1.1']
print sorted( [ [int(v) for v in x.split(".")] for x in vsn_list ] )
When you compare strings, they are compared character by character so any string starting with '2' will sort before a string starting with '8' for example.

How to return a string from an array [duplicate]

This question already has answers here:
How can I convert each item in the list to string, for the purpose of joining them? [duplicate]
(9 answers)
Closed 7 years ago.
keyword = raw_input ("Enter your keyword") *10000
keyword = keyword.lower()
keywordoutput = []
for character in keyword:
number = ord(character)
keywordoutput.append(number)
input1 = raw_input('Write Text: ')
input1 = input1.lower()
output1 = []
for character in input1:
number = ord(character)
output1.append(number)
output2 = [x + y for x, y in zip(output1, keywordoutput)]
print output2
That is my code so far. I am trying to create a program that uses a simple Vigenere Cypher to encrypt an inputted text. The code works perfectly, yet I am having an issue implimenting new code to return a string of 'output2'.
I get 'output2' easily, but from there i need to make it a simple string.
Eg: [1, 2, 3, 4]
becomes (1234)
I have tried, but I cant seem to implement such a thing into my code.
First you have to convert numbers into text.
output2 = map(str, output2)
Then you can use join to concatenate elements.
print "".join(output2)
Or in one line:
print "".join(map(str, output2))
try this
print ''.join(str(i) for i in output2)
One step use -> join:
output2 = ''.join([str(x + y) for x, y in zip(output1, keywordoutput)])
Check: https://docs.python.org/2/library/string.html#string.join
As the function is expecting a string type you must covert the numeric result x + y.

Categories

Resources