replace characters in a input text using lists - python

I wanna use lists;
by that I mean a = b in a list
let = {
"a", "b" (meaning a is b)
}
then how can I use this list to replace all characters in a input string
string = "stringa"
characters = [
"a", "b",
]
dic = {}
for l1 in zip(characters):
dic[l1]
result = ""
for letter in string:
result = result + dic[letter]
print(result)
input('Press Any Key To Exit')
I tried this but it didnt work any help is appeciarated

I think your problem is in the zip(characters) line.
you need more than one list inorder to zip.
When you do zip to just one list, the output is as seen here:
c = ['a','b']
for i in zip(c):
print(i)
# ('a',)
# ('b',)
and this also is what your error shows you KeyError: ('a',)
EDIT:
if you want to have "stringa" converted to "stringb" you have another issue.
What you need to do is:
string = "stringa"
dic = {'a':'b', 'b':'a'}
result = ""
for letter in string:
if letter in dic.keys():
letter = dic[letter]
result+=letter
print(result)
# stringb

When converting a list into a dictionary, you use slices to turn the list into two, for zipping together. zip returns a tuple iterator, so you need two for loop variables:
for l1, l2 in zip(characters[::2], characters[1::2]):
dic[l1] = l2
dic[l2] = l1
The [::2] gets every other character starting with the first one. The [1::2] gets every other character starting with the second one.
If you want to avoid a dictionary, and do a two-way replacement, then one way to do it is to do the replacements in the zip loop:
result = string
for l1, l2 in zip(characters[::2], characters[1::2]):
result = result.replace(l1, '#')
result = result.replace(l2, l1)
result = result.replace('#', l2)
The # is a temporary placeholder to avoid undoing the replacement we just did. You can set that to be any character that won't show up in the strings.

Related

I Would Like To Replace A Word With A Letter In Python

Code:
list = ['hello','world']
list2 = ['a','b']
string = 'hello'# should output a
string_fin = ''
for s in string:
for i, j in zip (list, list2):
if s == i:
string_fin += j
print(string_fin)
I want to write hello or world in string = '' and to get the output a or b
I get which is nothing
The reason this is happening is because hello and world have more characters than a and b when I try something that has the same amount of characters as a or b it works
Please help
Thanks
Your program's main loop never runs because string is empty! So your program is basically:
list = ['hello','world']
list2 = ['a','b']
string = ''
string_fin = ''
print(string_fin)
Although based on how you worded your question, it is really hard to understand what you are trying to accomplish, but here is my go.
You have two lists: list1 and list2 (Please do not name your list list as it is a reserved keyword, use list1 instead!)
You want to check whether each word in your string matches with any word in your first list.
If it matches you want to take the corresponding word or letter from your second list, and append it into the string string_fin.
Finally, when you looped through all the words in the list, you print the content of string_fin.
The correct way to do this would be to split your string variable, and get each word stored in it.
string = 'hello or world'
stringWords = string.split()
Now, stringWords contains ['hello', 'or', 'world']. But I think you are not interested in the item or. So you can remove this item from the list, by using remove().
if 'or' in stringWords:
stringWords.remove('or')
Now you have the words that you are interested in. And we want to check whether any word in the first list matches with these words. (Remember, I renamed the first list from list to list1 to prevent any unexpected behavior.)
for word in stringWords:
tempIndex = list1.index(word)
temp = list2[tempIndex]
string_fin += temp
However, using index raises ValueError if a match is not found, so depending on your program logic, you may need to catch an exception and handle it.
The string string_fin will now contain ab or a or b depending on the value inside string.
Now, since you wanted to print something like a or b, you can instead create a list and store the matching words in it, and then, join this list using or separator.
string_fin = (' or ').join(tempList)
A complete program now will look like this:
list1 = ['hello', 'world']
list2 = ['a', 'b']
string = 'hello or world'
tempList = []
stringWords = string.split()
if 'or' in stringWords:
stringWords.remove('or')
for word in stringWords:
tempIndex = list1.index(word)
temp = list2[tempIndex]
tempList.append(temp)
string_fin = ' or '.join(tempList)
print(string_fin)
Better to store your lists as a dictionary, so you can do an easy lookup:
mapping = {'hello':'a', 'world':'b'}
string = 'hello or world'
out = []
for s in string.split():
out.append( mapping.get( s, s ) )
print(' '.join(out))
Purists will note that the for loop can be made into a one-liner:
mapping = {'hello':'a', 'world':'b'}
string = 'hello or world'
out = ' '.join(mapping.get(s,s) for s in string.split())
print(out)

I want to change an element in list from string format to integer, how should i approach it?

So I just went into python not too long ago, it is to develop my OCR project. I want the software to detect the character "A" and convert it to a set of integers like 101.
list=['haha', 'haaa']
I am thinking of using a dictionary with keys and item to try replacing it. I added a define function for the process. I use this method I found in other post but it doesn't work.
Dictionary={'a':101,'h':111}
for a,b in Dictionary.items():
list = list.replace(a.lower(),b)
print (list)
First, you should make sure your list variable is not list as this is a keyword in python. Then, loop through the items and replace the key with the value at the key as such:
l = ['haha', 'haaa']
refDict = {'a':101,'h':111}
for i, item in enumerate(l):
for key in refDict:
item = item.replace(key, str(refDict[key]))
l[i] = item
Output after this code:
['111101111101', '111101101101']
Never use list as variable since it is already a python function.
One can use this:
l = ['haha', 'haaa']
conv_dict = {'a':101, 'h':111}
for j, ele in enumerate(l):
ele = list(ele)
for i, char in enumerate(ele):
ele[i] = conv_dict[char.lower()]
l[j] = int( ''.join(map(str, ele)))
print(l)
>> [111101111101, 111101101101]
This is not a robuste solution, since every character should be in the conv_dict to convert the char to int.
How it works:
Go over each word in the list
Convert string to list, with each char as element
Go over each character
Replace character with integer
Join the integers to one string and then convert it back to integer
Repeat for every string in list
I'm not very sure what output you're expecting but your question seems like you want the equivalent value of the elements in the dictionary to be substituted by the key values in the dictionary.
As each element of lst is considered in the first loop, an empty string ans is initialized. It then iterates through every character in the nested loop which concatenates the dictionary equivalent of each character into ans. The end result is appended into output
Dictionary={'a':101,'h':111}
lst=['haha', 'haaa']
output = []
for i in lst:
ans = ""
for j in i:
ans+=str(Dictionary[j])
output.append(ans)
print(output)
Output
['111101111101', '111101101101']
It sounds to me like you do not need to map the characters to a specific integer, just any unique integer. I would recommend not creating your own dictionary and using the standardized ascii mappings for characters (https://www.asciitable.com/). Python has a built-in function for converting characters to that value
Here is what that might look like (as others have pointed out, you also shouldn't use list as a variable name.
words = ['haha', 'haaa']
conversions = []
for word in words:
converted_word = []
for letter in word:
converted_word.append(ord(letter))
conversions.append(converted_word)
print(conversions)
This prints:
[[104, 97, 104, 97], [104, 97, 97, 97]]
How about str.translate?
lst = ['haha', 'haaa']
table = {ord('a'): '101', ord('h'): '111'}
lst = [s.translate(table) for s in lst]
print(lst)
Output (Try it online!):
['111101111101', '111101101101']

Split List based on range into multiple list :PYTHON

I have a small doubt , and i was not able to solve it , consider i have a list seperated with comma , and the data is dynamic may be 2 data or more than that
example : listVaue = ['Server1,Stop,Server2,START,.....,ServerN,StartN/StopN']
where N is a number
so if i have to split this into something like [[Server1,Stop],[Server2,Start2],....[ServerN,StartN/StopN]]
Is this possible . I wrote a code , but it is not working properly
listVaue = ['Server1,Stop,Server2,START']
c_index = listVaue.index("Stop")
l2 = listVaue[:c_index]
print(l2)
Can anyone help me solve this problem
This should work:
listValue = ["server1, stop, server2, start"]
listValue = listValue[0].split(",")
l2 = [[first_item, second_item] for first_item, second_item in zip(listValue[0::2], listValue[1::2])]
If you have a list defined as:
listVaue = ['Server1,Stop,Server2,START']
it actually only has one value, which is a string of value 'Server1,Stop,Server2,START'. If you can define a different list, I would suggest trying to do:
listVaue = ['Server1', 'Stop', 'Server2', 'START']
or even a list of tuples, if you would like values to be correspondent:
listVaue = [('Server1', 'Stop'), ('Server2', 'START')]
Now, if you don't have control over the input data (and therefore cannot change the original list), what you can do is to first split all values by comma and then aggregate them 2 by 2.
# Original list
listVaue = ['Server1,Stop,Server2,START']
# Split string into separate values
# Take the first element - from your code it looks
# like you only have a continuous string
new_list = listVaue[0].split(',')
# If you know that the list length will always be even, you can
# aggregate them 2 by 2 using the following code:
l2 = [(new_list[i], new_list.pop(i + 1)) for i in range(len(new_list) // 2)]
l2
>>> [('Server1', 'Stop'), ('Server2', 'START')]
What the code does is basically to get elements in position i and the next one as well (i + 1), removing the latter, whilst iterating through half the length of the list. Because you change its size as you iterate, always removing the second item, you'll end up only iterating through the original indexes 0, 2, 4, 6, 8..., whilst also retrieving their counterpart (1, 3, 5, 7, 9...).
Please note that changing the size of a list whilst you iterate is not generally a good practice, but because we are copying the original list, it shouldn't be a big problem for your case.
You can also change my code to whatever suits you, and you're probably better off with a normal for loop instead of a list comprehension:
listVaue = ['Server1,Stop,Server2,START']
new_list = listVaue[0].split(',')
l2 = []
for i in range(len(my_list) // 2):
# Change square brackets to round ones if you want a tuple (immutable) instead
l2.append([new_list[i], new_list.pop(i + 1)]
print(l2)
Try this:
listVaue = ['Server1,Command1,9182,Running,START,Server2,Command2,8888,Running,RESTART,ServerN,CommandN,N,Running,restart']
listVaue = listVaue[0].split(',')
a = ['START', 'RESTART', 'STOP', 'BOUNCE']
s = []
l2 = []
for i in listVaue:
s.append(i)
if i.upper() in a:
l2.append(s)
s = []

max() arg is empty error when joining strings

I'm new to coding and I was trying to make a script that will join the tuples inside 'sl', which are a sequence of letters, into a new tuple called 's' with the items as strings. and then print out the longest string inside s.
this is the code I came up with (or short version). When I try to print the max item of 's' in this code, returns a
max() arg is empty
error.
sl = [['m','o','o','n'],['d','a','y'],['h','e','l','l','o']]
s = []
s = (''.join(i) for i in sl) # join the letters inside sl, put them into s
print(max(s, key=len)) # print longest string inside s
but I still can iterate throught s with:
for i in s:
print(i)
and will print the words inside s, joined
I suppose that (''.join(i) for i in sl) isnt properly joining them as strings. Is there a way that the words inside 's' are join as strings?
It works, just replace () with []
sl = [['m','o','o','n'],['d','a','y'],['h','e','l','l','o']]
s = []
s = [''.join(i) for i in sl]
print(s)
print(max(s, key=len))

Append/pop specific element of a string to the list when iterating over it

I want to know how to append and pop only specific element of a string
def letter(item):
lst = []
for i in item:
if 'a' in item:
# not sure what to put here
return lst
Output:
lst = ['a']
I only want the function to append the letter 'a' in 'apple', is that possible?
And is there a way to only remove a specific letter from a string using the list.pop() function?
If you need to use list.pop(), you can first convert your string to a list:
def find_letter(item):
lst = []
item=list(item) #convert your string to list
for index,letter in enumerate(item):
if letter=='a':
lst.append(letter) # add 'a' to your empty list
item.pop(index) # remove 'a' from the original string
item="".join(item) # convert back your list to a string
return lst,item
This gives the following output:
>>> find_letter("apple")
>>> (['a'], 'pple')
Note that you can do much simpler using list comprehension:
def find_letter(item):
word="".join([letter for letter in item if letter!='a'])
lst=[letter for letter in item if letter=='a']
return lst,word

Categories