python string remove without using internal function [duplicate] - python

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.

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

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

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('\\\\','\\').

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

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(" ", "")

Swapping string case in Python [duplicate]

This question already has answers here:
How can I invert (swap) the case of each letter in a string?
(8 answers)
Closed 7 years ago.
I'm rank new in Python, thus the question,
I'm trying to solve a simple problem, where the program takes in a simple string and swaps all the cases. Thus if we enter
SimPLE
We should get
sIMple
This is my code
def main():
oldStr = input()
for s in oldStr:
if s.islower():
s.upper()
elif s.isupper():
s.lower()
print(oldStr)
if __name__ == "__main__" : main()
It just returns the same string. Any help appreciated.
As a generator expression:
mystr = "SimPLE"
print("".join(c.upper() if c.islower() else c.lower() for c in mystr))
The breakdown of the above is:
c.upper() if c.islower() else c.lower()
is an conditional expression that will convert a character from upper to lower case and vice versa.
Then,
(... for c in mystr)
is a generator expression, which is somewhat like a list that is generated on-the-fly.
Finally:
".join(...)
will join any sequence of strings together with nothing ("") between them.
Do this in one fell swoop with a string join on a list comprehension of individual characters:
outstr = ''.join([s.upper() if s.islower() else s.lower() for s in oldStr])
print(outstr)
Input & Output:
sIMple
SimPLE
Strings are immutable. What this means is that when you use the function s.upper(), it is not setting that letter in str to be uppercase, it simply returns that letter in uppercase.
Here is some code that works:
def main():
oldStr = input()
newStr = ""
for s in oldStr:
if s.islower():
newStr+=s.upper()
elif s.isupper():
newStr+=s.lower()
print(newStr)
Notice now that we are creating a new string and simply adding the letters at each point in the forloop as opposed to changing those letters in str.
You are running each character through lower() and upper(), but these functions do not change the character.
Instead, they return the modified version of the character. The original character s will stay as it is.
You should build a new string based off the return values of lower() and upper(), and return that string.
1) you need to put the main() call on new line, as python relies on whitespace heavily for program structure
2) s is a temporary variable created for the purpose of the for statement. It doesn't actually reference the character in the string
Essentially what is going on is that s has the same value as the character in the string, but it IS NOT ACTUALLY the character in the string.

Categories

Resources