Properly escaping a desired character without duplicating the backslash [duplicate] - python

This question already has answers here:
Why do backslashes appear twice?
(2 answers)
Closed 2 years ago.
So I have a function that takes a string, iterates over a set of characters and returns a string with a backslash added to all the occurences of any character in that particular string:
def re_escape(string):
res = "|\^&+\-%*/=!>"
for i in res:
if i in string:
a = string.split(i)
adjusted = ""
for y in a:
adjusted+="\\"+i+y
adjusted = adjusted[2:]
string = adjusted
print(string)
return string
Giving this function the string " <br>" returns " <br\>", as desired.
However, going back to the part of the program calling this function and receiving the string as a return value, trying to print it results in " <br\\>" being printed. Is there any way to prevent it from adding the second undesired backslash?

Give it a try: string.replace('\\\\','\\').

Related

Removing a character (number, letter, anything) in a string that is the same as the one that came before or after? (Python) [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 3 months ago.
So, I've seen a lot of answers for removing duplicate characters in strings, but I'm not trying to remove all duplicates - just the ones that are beside each other.
This is probably a lot more simple than what I'm doing, but this is what I've been attempting to do (and failing miserably at)
for j in range(2, len(string)-1):
char = string[j]
plus = string[j+1]
minus = string[j-1]
if char == plus or char == minus:
string.replace(char, "")
For reference, the code SHOULD act as:
input: ppmpvvpmmp
output: pmpvmp
But instead, the output does not change at all.
Again, I'm aware that this is most likely very easy and I'm overcomplicating, but I'm genuinely struggling here and have tried a lot of similar variations
I would use a regular expression replacement here:
inp = "ppmpvvpmmp"
output = re.sub(r'(\w)\1', r'\1', inp)
print(output) # pmpvpmp
The above assumes that a duplicate is limited to a single pair of same letters. If instead you want to reduce 3 or more, then use:
inp = "ppmpvvvvvpmmmp"
output = re.sub(r'(\w)\1+', r'\1', inp)
print(output) # pmpvpmp

python string remove without using internal function [duplicate]

This question already has answers here:
Removing space in a string without using built in methods
(4 answers)
How to print without a newline or space
(26 answers)
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 months ago.
I'm a freshman CS student. This is one of the exercises we had in class:
Create a function called remove_space(string):
The function takes in a string as input
The function returns a new string, which is generated by removing all the spaces in the given string.
Example: remove_space(“welcome to computer science”) returns “welcometocomputerscience”
I have looked around for solutions online but we aren't allowed to use any advanced functions like split(), replace(), join() or anything of that sort. I'm looking for the most primitive way to solve this without using those that would make sense coming from a freshman CS student.
This is what I have so far:
def remove_space(string):
temp = ""
for char in string:
if char == " ":
char = temp
print(char)
print("----------------#1---------------")
remove_space("Welcome to computer science")
What am I doing wrong?
def remove_space(string):
result_string = ''
for character in string:
if character != ' ':
result_string += character
return result_string
remove_space('welcome to computer science')
Result:
'welcometocomputerscience'
Try this:
Create a variable temp, concat the char if it is != " " and then return temp
def remove_space(string):
temp = ""
for char in string:
if char != " ":
temp += char
return temp
print(remove_space("welcome to computer science"))
Simple answer:
When you write char = temp, you are basically assigning the variable to a new value instead of overriding t in the original string.
What you are doing is equivalent to:
a = 3
b = a
b = 2
Even though you tell b to be equal a, you reassign it later to be 2. If you print(a) you will see that its value will still be the same.
CS-Dojo has a great video on this https://youtu.be/Z1Yd7upQsXY?t=1002 you can start at minute 16 where he explains variable assignment.

Why is my vowel removal function not working? (Python 2.7) [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 3 years ago.
I'm working through the Python course on codecademy and trying to create a python function that removes vowels in a string and returns the newly modified string.However the function returns the string without any modification (i.e. if I call anti_vowel("abcd") it returns "abcd")
After using a print statement it appears the for loop only runs once, irrespective of the length of the string.
def anti_vowel(string):
for t in string:
if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string.replace(t, " ")
print "test"
print string
return string
Strings in Python are immutable, so you will need to make an assignment back to the original string with the replacement on the RHS:
if (t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string = string.replace(t, " ")
But, you could also just re.sub here:
string = re.sub(r'[aeiou]+', '', string, flags=re.IGNORECASE)
You have the return statement inside the for a loop that is why your code is your loop is executing exactly once. Place it outside the loop and your code will work fine.
def anti_vowel(string):
for t in string:
if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string.replace(t, " ")
print "test"
print string
return string
For replacing the vowel characters, you cannot replace in the existing variable as strings in python are immutable. You can try this
def anti_vowel(string):
for t in string:
if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string=string.replace(t, " ")
print "test"
print string
return string

Checked docs on String.replace() not working anyway Python [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 4 years ago.
I have read all the python docs on String.replace, yet I am still having trouble with my code. My code is as follows:
#within a class
def fixdata(self):
global inputs_list
for i in range(0, len(inputs_list)):
inputs_list[i].replace("\n", "")
print(inputs_list[i]) # to check output
What I am hoping for is that all \n characters (newlines) are replaced with empty string ""so that trailing newlines are removed. .strip(), .rstrip(), and, I'm assuming, .lstrip() do not work.
Dok: string.replace()
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
You replace and throw the copy away:
#within a class
def fixdata(self):
global inputs_list
for i in range(0, len(inputs_list)):
inputs_list[i].replace("\n", "") # Thrown away
print(inputs_list[i]) # to check output
More doku:
lstrip() / rstrip()/ strip()
Return a copy of the string ...
Fix:
def fixdata(self):
global inputs_list # a global in a class-method? pass it to the class and use a member?
inputs_list = [item.rstrip() for item in input_lists]
You need to assign the new string like this:
inputs_list[i] = inputs_list[i].replace("\n", "")

Trying to remove white spaces in python .replace not working [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 6 years ago.
For some reason string.replace(" ", "") is not working.
Is there another way of removing white spaces from a string?
Why is .replace not working in this particular situation?
string = input('enter a string to see if its a palindrome: ')
string.replace(' ', '') # for some reason this is not working
# not sure why program will only work with no spaces
foo = []
bar = []
print(string)
for c in string:
foo.append(c)
bar.append(c)
bar.reverse()
if foo == bar:
print('the sentence you entered is a palindrome')
else:
print('the sentence you entered is not a palindrome')
replace() returns a new string, it doesn't modify the original. Try this instead:
string = string.replace(" ", "")

Categories

Resources