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

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

Related

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.

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

Capitalize first letter ONLY of a string in Python [duplicate]

This question already has answers here:
Capitalize a string
(9 answers)
How can I capitalize the first letter of each word in a string?
(23 answers)
Closed 6 years ago.
I'm trying to write a single line statement that assigns the value of a string to a variable after having ONLY the first letter capitalized, and all other letters left unchanged.
Example, if the string being used were:
myString = 'tHatTimeIAteMyPANTS'
Then the statement should result in another variable such as myString2 equal to:
myString2 = 'THatTimeIAteMyPANTS'
Like this:
myString= myString[:1].upper() + myString[1:]
print myString
Like Barmar said, you can just capitalize the first character and concatenate it with the remainder of the string.
myString = 'tHatTimeIAteMyPANTS'
newString = "%s%s" % (myString[0].upper(), myString[1:])
print(newString) # THatTimeIAteMyPANTS

How do I turn only the first letter uppercase? [duplicate]

This question already has answers here:
Capitalize a string
(9 answers)
Closed 6 years ago.
I have this:
word = raw_input("enter a word")
word[0].upper()
But it still doesn't make the first letter uppercase.
.upper() returns a new string because strings are immutable data types. You ought to set the return value to a variable.
You can use .capitalize over .upper if you want to make only the first letter uppercase.
>>> word = raw_input("enter a word")
>>> word = word.capitalize()
Please note that .capitalize turns the rest of the characters to lowercase. If you don't want it to happen, just go with [0].upper():
word = word[0].upper() + word[1:]

Categories

Resources