Avoid overlap when using replace [duplicate] - python

This question already has answers here:
Python replace function [replace once]
(6 answers)
Replace 2 characters within a reversed string at once
(2 answers)
Closed 4 years ago.
I'm playing around with a simple crypting program, and I want it to work so that every specific symbol, always will turn into another specific symbol. That might not be the best description, but I don't know how else to put it... For an example:
"a" is going to be "h"
"A" is going to be "k"
"h" is going to be "W"
text_1 = "aAh"
text_2 = text_1.replace('a', 'h')
text_3 = text_2.replace('A', 'K')
text_4 = text_3.replace('h', 'W')
print text_4
#the output is "WKW"
#I need the output to be "hKW"
The problem is, that I'm using the replace-command for every single symbol-replacement, so if we suppose that the codes are typed in the same order as our example, and the message I want to crypt is "aAh", then I would like the crypted output to be "hKW" but actually we get this output instead "WKW".
I know why this is happening, so my question is:
How do I get the program to crypt the message the way I intended it to do?

The problem you have is that you're applying your changes to intermediate strings (so the previous changes will affect the result)
Consider trying to calculate the intended changes on the initial string for each character and build the final string after.

You can use a dict for your character mapping and then use a generator expression to translate the characters:
m = {'a': 'h', 'A': 'K', 'h': 'W'}
print(''.join(m.get(c, c) for c in text_1))
This outputs:
hKW

Related

Assigning variables to split strings [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Split a string with unknown number of spaces as separator in Python [duplicate]
(6 answers)
Closed 2 years ago.
I am trying to split a string into several variables to eventually send each one as an instruction for one of six stepper motors. A string will be in a format like so:
D2 R' D' F2 B D R2 D2 R' F2 D' F2 U' B2 L2 U2 D R2 U
The issue is the steps within the string (e.g. D2 or R' or B) are all varying in length, so using step as a fixed length provides issues when recalling the individual sections (the varying lengths means that sometimes I will get part of one solution or a blank space then a letter). Also using something like unpacking doesn't work as the amount of steps in the string varies. So, how can I cut up a string like the one shown below, so I can assign each step to a individual variable?
From looking at a previous question (Python - split string into smaller chunks and assign a variable) I have realised I can do something along these lines:
finalstate = input("enter solution: ")
finalstate.split
step = 2
solution_steps = [finalstate[i:i+step] for i in range(0, len(finalstate),step)]
And then call upon the different chunks of the solution like so:
print(Solution_steps[0])
However, in that solution they wanted the string to be separated by a determined length and mine will vary.
You need to call the split method by putting () after it. And it returns a list, you need to assign that somewhere.
finalstate = input("enter solution: ")
words = finalstate.split()
step = 2
solution_steps = [words[i:i+step] for i in range(0, len(words),step)]
Value of solution_steps:
[['D2', "R'"], ["D'", 'F2'], ['B', 'D'], ['R2', 'D2'], ["R'", 'F2'], ["D'", 'F2'], ["U'", 'B2'], ['L2', 'U2'], ['D', 'R2'], ['U']]

Checking if a number is present in string [duplicate]

This question already has answers here:
Check if a string contains a number
(20 answers)
Closed 2 years ago.
I have a working function that takes an input as string and returns a string. However, I want my function to return an empty string ("") if the input contains any number in whatever position in the string.
For example :
>>> function("hello")
works fine
>>> function("hello1")
should return ""
The main thing you need for that is the method "isdigit()" that returns True if the character is a digit.
For example:
yourstring="hel4lo3"
for char in yourstring:
if char.isdigit():
print(char)
Will output 4 and 3.
I think it is a good exercise for you trying to do your code from that!

How does the count function count? [duplicate]

This question already has answers here:
Why are str.count('') and len(str) giving different output?
(3 answers)
How does the count() method work? [duplicate]
(1 answer)
Closed 4 years ago.
This is a short one, yet very irritating. I know I can count the amount of times a string occurs within another string like this:
'banana'.count('a')
>>>3
meaning that banana contains the letter "a" 3 times.
This is where it gets kind of weird.
My first confusion is - when I do 'foo'.count(''), what does Python look for?
is '' == None == anything?
It doesn't seem to be the case, but then again, what IS '' logically speaking? And more importantly, why does
'test'.count('')
>>>5
return one more than the length of the string?
What the hell is included in a string that's always 1 higher than the amount of letters? the void?
EDIT: the ' character twice looks like one " character. I am talking about two times ' here, to avoid confusion
EDIT2: There seems to be some confusion about how the amount of '' happen. Refer to comments below.
Every string1 can be thought of as:
any_string = "" + "".join(any_string) + ""
which contains exactly len(any_string) + 1 instances of ''.
For "foo" for example, it would be:
"" + "f" + "" + "o" + "" + "o"+ ""
# |----- from join -------|
As it can be seen there are 4 instances of "" in it.
Note however, that this is a problem where no answer or all answers could somehow support a case for themselves. It get's philosophical:
How much nothing is contained in nothing?
How much nothing is contained in something?
This answer tries to explain the convention used by Python and does not intend to suggest that this is the way all languages do it \ should be doing it; it is just how Python does it.
1Empty strings are an exception and are handled differently; they simply return 1; which is yet another convention.
str.count(sub)
Counts the number of occurrences of sub in str.
Since strings are sequences, it basically counts the number of splits sub would cause in str.
An empty string is at the beginning, between each character, and at the end.
Hence, why when you use 'test', which has a len of 4, you get 5 occurrences of sub ('').

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

Python print list of sets without brackets [duplicate]

This question already has answers here:
Removing set identifier when printing sets in Python
(5 answers)
Closed 9 years ago.
I have a list of sets (using Python).
Is there a way to print this without the "set([])" stuff around it and just output the actual values they are holding?
Right now I'm getting somthing like this for each item in the list
set(['blah', 'blahh' blahhh')]
And I want it to look more like this
blah,blahh,blahhh
Lots of ways, but the one that occurred to me first is:
s = set([0,1])
", ".join(str(e) for e in s)
Convert everything in the set to a string, and join them together with commas. Obviously your preference for display may vary, but you can happily pass this to print. Should work in python 2 and python 3.
For list of sets:
l = [{0,1}, {2,3}]
for s in l:
print(", ".join(str(e) for e in s))
I'm assuming you want a string representation of the elements in your set. In that case, this should work:
s = set([1,2,3])
print " ".join(str(x) for x in s)
However, this is dependent on the elements of s having a __str__ method, so keep that in mind when printing out elements in your set.
Assuming that your list of sets is called set_list, you can use the following code
for s in set_list:
print ', '.join(str(item) for item in s)
If set_list is equal to [{1,2,3}, {4,5,6}], then the output will be
1, 2, 3
4, 5, 6

Categories