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 8 years ago.
I'm trying to remove a set of characters from a larger string. Here's what I've tried:
string = 'aabc'
remove = 'ac'
for i in remove:
string.replace(i, '', 1)
print(string)
I keep getting back my original string when I run this. The variable i is getting the characters 'a' and then 'c'. The replace function works for me if i do string.replace('a', '', 1). Why isn't this working or is there a simpler way to do this?
Strings are immutable in python, so string.replace() does not mutate the string; it returns a new string with the replacements.
Try this:
string = string.replace(i, '', 1)
replace returns a new string.
Strings in python are immutable.
As such, you must assign the return value:
string_new = "ABCD".replace("A","Z")
A new string will be generated as Strings are immutable...
Try this -
string = 'aabc'
remove = 'ac'
for i in remove:
result = string.replace(i, '', 1)
print(result)
As Strings are immutable you cant use replace with just string.replace().
As a better way use set :
>>> s='aabcc'
>>> s=''.join(set(s))
'acb'
Related
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.
Lest say I have string like this:
string = "hello world"
I want to have only praticular letter uppercased so if i choose second letter my output should look like this:
hEllo wold
But if i try for example:
string[1].upper()
My output is:
hello world
And not:
hEllo wold
I dont know why...
This line:
string[1].upper()
Isn't doing what you think. Sure, it uppercases the value in string[1], but it returns a new string with the result! - because in Python strings are immutable. Now, you'd be tempted to think that this would fix it:
string[1] = string[1].upper()
... But no, this will fail because once again - strings are immutable. You have no choice but to create a new string, with some logic to tell which positions you want to uppercase. For example, to uppercase the value at index = 1:
''.join(c.upper() if i == 1 else c for i, c in enumerate(string))
To capitalize only one letter of a string you have to capitalize the part of the string starting from the nth position, and assign it back to the variable:
string = string[:n] + string[n:].capitalize()
In Python Strings are not Modifiable hence the operation that you specified would not work.
In order to make this work,you can convert the string to a list and then convert a particular character to uppercase and then join the result back into a string.
sample_str="hello world"
sample_list=list(sample_str)
sample_list[2]=sample_list[2].upper()
print(''.join(str(i) for i in sample_list))
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
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", "")
This question already has answers here:
Replace part of a string in Python?
(3 answers)
Closed 4 years ago.
I'm trying to remove or ignore the ' symbol (Apostrophe) within a list of strings. I don't know if my for loop is just plain wrong or what:
n = ["a", "a's", "aa's"] #example list
for i in n:
i.strip("'")
strip won't work here use replace,
In [9]: [i.replace("'",'') for i in lst]
Out[9]: ['a', 'as', 'aas']
Two problems here.
First, strip doesn't work in the middle of the string, you have to use `replace("'", "")
Second, and more important, strings are immutable. Even if i.strip(...) did what you want, it would not change i. It would just produce a new string. So, you have to store that string.
Sum up, try something like
n = [i.replace("'", "") for i in n]
This question already has answers here:
Python: Cut off the last word of a sentence?
(10 answers)
Closed 8 years ago.
Is there any efficient way to select the last characters of a string until there's a whitespace in Python?
For example I have the following string:
str = 'Hello my name is John'
I want to return 'John'. But if the str was:
str = 'Hello my name is Sally'
I want to retrun 'Sally'
Just split the string on whitespace, and get the last element of the array. Or use rsplit() to start splitting from end:
>>> st = 'Hello my name is John'
>>> st.rsplit(' ', 1)
['Hello my name is', 'John']
>>>
>>> st.rsplit(' ', 1)[1]
'John'
The 2nd argument specifies the number of split to do. Since you just want last element, we just need to split once.
As specified in comments, you can just pass None as 1st argument, in which case the default delimiter which is whitespace will be used:
>>> st.rsplit(None, 1)[-1]
'John'
Using -1 as index is safe, in case there is no whitespace in your string.
It really depends what you mean by efficient, but the simplest (efficient use of programmer time) way I can think of is:
str.split()[-1]
This fails for empty strings, so you'll want to check that.
I think this is what you want:
str[str.rfind(' ')+1:]
this creates a substring from str starting at the character after the right-most-found-space, and up until the last character.
This works for all strings - empty or otherwise (unless it's not a string object, e.g. a None object would throw an error)