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 have converted the binary result of a URL request into a text string, then attempted to replace the instances of '\r' with '' and '\n' with ' ' using the following code:
newvar = str(oldvar)
newvar.replace('\r', '')
newvar.replace('\n', ' ')
However when the variable newvar is printed to the log and written out to a file it retains the '\r' and '\n'. What am I doing wrong? I'm using the exact syntax suggested and that I had already read online.
Thanks
replace doesn't modify the string, as strings are immutable; it creates a new string, which you need to assign:
newvar = newvar.replace('\r, '')
You need of set var to do it:
newvar = str(oldvar)
newvar = newvar.replace('\r', '')
newvar = newvar.replace('\n', ' ')
Then print:
print newvar
The idea is that you assign the replacements to the already existing variable like that:
newvar = (str(oldvar))
newvar = newvar.replace('\r','')
newvar = newvar.replace('\n','')
As with many problems, this boils down to Read The Friendly Manual:
str.replace(old, new [, count])
Return a copy [emphasis mine] of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
This doesn't change the string. It returns a copy of the string, modified.
Related
This question already has answers here:
Python split() without removing the delimiter [duplicate]
(4 answers)
Closed 11 months ago.
Is it possible to separate the string "a!b!" into two strings "a!" and "b!" and store that in a list? I have tried the split() function (and even with the delimiter "!"), but it doesn't seem to give me the right result that I want. Also, the character "!" could be any character.
How about :
string = 'a!ab!b!'
deliminator = '!'
word_list = [section+deliminator for section in string.split(deliminator) if section]
print(word_list)
Output :
['a!', 'ab!', 'b!']
split() is used when you need to seperate a string with particular character. If you want split a string into half, Try this
s = "a!b!"
l = [s[ : len(s)//2], s[len(s)//2 : ]]
# output : ["a!", "b!"]
This question already has answers here:
How do the .strip/.rstrip/.lstrip string methods work in Python?
(4 answers)
Closed 1 year ago.
I feel like I have a very straightforward piece of code. I have a file name that follows the form of 'stuff_category.csv'. I'm trying to remove 'stuff_' and '.csv', so that I will be left with 'category', which I need for the next piece of code. 'stuff_' can be many different things, so I can't use the replace() function. Right now I have
filename = "stuff_category.csv"
category = filename.lstrip('_').rstrip('.')
But if I try print(category), or even print(category.lstrip('_')), it just returns the original file name. What am I missing?
You could do it using removeprefix and removesuffix (Python 3.9) rather than lstrip and rstrip:
filename = "stuff_category.csv"
print(filename.removeprefix('stuff_').removesuffix('.csv')) #category
Or using Slicing with startswith endswith (Python 3.8):
start = "stuff_"
end = ".csv"
if filename.startswith(start):
filename = filename[len(start):]
if filename.endswith(end):
filename = filename[:-len(end)]
print(filename) #category
Or even use Slicing with just index:
print(filename[filename.index('_')+1:filename.index('.')]) #category
You're missing the documentation for these methods. They don't use the provided character as a delimiter, they remove the characters as if a substring.
lstrip(self, chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
Try this:
filename = "stuff_category.csv"
category = filename.lstrip('stuff_').rstrip('.csv')
Consider using a regular expression or str.split instead of lstrip/rstrip if "stuff_" isn't constant.
This question already has answers here:
How do I remove a substring from the end of a string?
(23 answers)
Closed 2 years ago.
I am kind of noob in python and struck in middle of code. I want to trim my string.
For example- my string is "bangalore store 1321" and i want to trim it to "banglore"
Looks like you want to keep the first word (which is not "trimming" though). So you do two things
break the string into a list of words (where "word" is something separated by spaces)
take the first element of that list
words = mystring.split(' ')
result = words[0]
For a slicing answer:
def sub_string(str, start,end):
return str[start:end]
You can also use split, by definition, this splits by spaces, if any other delimiter needed, you can identity it inside the split arguments split(',')
def split_string(str):
return str.split()
This function will return an array of strings. Choose whichever you want from this array
str="bangalore store 1321"
print(str.split(' ')[0])
Output
bangalore
You can use str's partition method to avoid creating a list like str.split
>>> first_word, _, _ = s.partition(' ') # _ is a convention for a throwaway variable
>>> print(first_word)
bangalore
str.partition takes one argument - the separator - and returns the parts of the string before and after the first occurrence of the separator.
This question already has answers here:
How do the .strip/.rstrip/.lstrip string methods work in Python?
(4 answers)
Closed 4 years ago.
Is there a reason why I am having this kind of string strip behavior ? Is this a bug or some string magic I am missing
# THIS IS CORRECT
>>> 'name.py'.rstrip('.py')
'name'
# THIS IS WRONG
>>> 'namey.py'.rstrip('.py')
'name'
# TO FIX THE ABOVE I DID THE FOLLOWING
>>> 'namey.py'.rstrip('py').rstrip('.')
'namey'
That's because the str.rstrip() command removes each trailing character, not the whole string.
https://docs.python.org/2/library/string.html
string.rstrip(s[, chars])
Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.
This also generates same result
>>> 'nameyp.py'.rstrip('.py')
'name'
You could try str().endswith
>>> name = 'namey.py'
... if name.endswith('.py'):
... name = name[:-3]
>>> name
'namey'
Or just str().split()
>>> 'namey.py'.split('.py')[0]
'namey'
This question already has answers here:
How to remove \n from a list element?
(15 answers)
Closed 7 years ago.
How can I delete a /n linebreak at the end of a String ?
I´m trying to read two strings from an .txt file and want to format them with os.path.join() method after I "cleared" the string.
Here you can see my try with dummy data:
content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']
for string in content:
print(string)
if string.endswith('\\\n'):
string = string[0:-2]
print(content)
You can not update a string like you are trying to. Python strings are immutable. Every time you change a string, new instance is created. But, your list still refers to the old object. So, you can create a new list to hold updated strings. And to strip newlines you can use rstrip function. Have a look at the code below,
content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']
updated = []
for string in content:
print(string)
updated.append(string.rstrip())
print(updated)
You can use rstrip function. it trims any 'empty' string including \n from the string, like below:
>>> a = "aaa\n"
>>> print a
aaa
>>> a.rstrip()
'aaa'
To remove only \n use this:
string = string.rstrip('\n')
When you do string[0:-2] you are actually removing 2 characters from the end, while \n is one character.
try:
content = map(lambda x: x.strip(), content)