Checked docs on String.replace() not working anyway Python [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 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", "")

Related

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

Python: .strip() method is not working as expected [duplicate]

This question already has answers here:
How do the .strip/.rstrip/.lstrip string methods work in Python?
(4 answers)
Closed 2 years ago.
I have two strings:
my_str_1 = '200327_elb_72_ch_1429.csv'
my_str_2 = '200327_elb_10_ch_1429.csv'
When I call .strip() method on both of them I get results like this:
>>> print(my_str_1.strip('200327_elb_'))
'ch_1429.csv'
>>> print(my_str_2.strip('200327_elb_'))
'10_ch_1429.csv'
I expected result of print(my_str_1.strip('200327_elb_')) to be '72_ch_1429.csv'. Why isn't it that case? Why these two result aren't consistent? What am I missing?
From the docs:
[...] The chars argument is a string specifying the set of characters to be removed. [...] The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped [...]
This method removes all specified characters that appear at the left or right end of the original string, till on character is reached that is not specified; it does not just remove leading/trailing substrings, it takes each character individually.
Clarifying example (from Jon Clements comment); note that the characters a from the middle are NOT removed:
>>> 'aa3aa3aa'.strip('a')
'3aa3'
>>> 'a4a3aa3a5a'.strip('a54')
'3aa3'

Can I uppercase particular letter in string in 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 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))

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

Why isn't this Python replace function 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 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'

Categories

Resources