for example input:
text = 'wish you “happy” every (day)'
expected output:
text = 'wish you (happy) every “day”'
I'd like to swap parentheses with quotations everywhere in an unknown text. I'm doing a school assignment and I'm NOT allowed to use list!!! As strings are immutable so I'm not sure what to do then. please help!
Here's a silly answer using string.replace():
text = 'wish you “happy” every (day)'
text = text\
.replace('”', '*')\
.replace('“', "^")\
.replace("(", '“')\
.replace(")", '”')\
.replace("*", ')')\
.replace("^", '(')
Since you have a list of characters to replace, build a dictionary of what character should be swapped with another character, then iterate through the string and create a new string which contains the original string with replaced letters. This way, you can have as many or as few strings in the switch dictionary as you want, and it will work without modification. Factored up to a larger scale, you might want to do something like store this dictionary elsewhere, for example if you're creating it based on user input that you get from an interface or a webapp. It's often good to separate the specification what you are doing from how you are doing it, because one can be treated as data (which characters to swap) whereas the other is logic (actually swapping them).
text = 'wish you “happy” every (day)'
newtext = ''
switch = {
'“': '(',
'”': ')',
'(': '“',
')': '”',
}
for letter in text:
if letter in switch: letter = switch[letter]
newtext += letter
The reason I took an iterative approach is because we are swapping characters, so if you replace all instances of each character at the same time, characters will get swapped back once you swap the next one unless you include an intermediate step such as *
in my silly answer or ###
in the other answer, which opens the possibility of collisions (if your text already contained ###
or *
it would incorrectly be replaced).
immutability of strings is why you have to create the newtext
string instead of replacing the characters in the original string as I iterate.