Delete /n at end of a String (Python) [duplicate] - python

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)

Related

How to split my string "a!b!" into a!, b! in python? [duplicate]

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!"]

Weird problem in python with removing \xa0 and other encoding when adding items to list [duplicate]

This question already has answers here:
How to remove \xa0 from string in Python?
(15 answers)
Closed 1 year ago.
I have the following code:
x = "$30.00\xa0USD\u202c"
e = x.strip()
print (e)
group = ["a", e.strip(), "b"]
print (group)
This is the result it gives me:
$30.00 USD‬
['a', '$30.00\xa0USD\u202c', 'b']
I want to remove the "\xa0" from the items that I add to the list but .strip() doesn't seem to be working, how do I solve this?
strip() strips whitespace from both sides and there is no whitespace to strip from the string you passed in. It's not clear what you hoped would happen or why; probably the proper solution is to fix whatever produced that string in the first place.
If you want to discard \xa0 then ... say so.
x = x.replace('\xa0', '')
If you want to extract only plain printable ASCII from the string, maybe try a regular expression.
import re
x = ' '.join(re.findall('[ -~]+', x))
If you want to strip \u202c, you can do that too, of course.
x = x.strip('\u202c\u202f')
(I threw in U+202F too just to show that it's easy to do.)
But again, the unholy mix of raw bytes and Unicode in your input string is likely a sign of corruption earlier in your processing. If you can fix that, maybe you will no longer need any of these.

remove certain charicters from a string python [duplicate]

This question already has answers here:
Remove specific characters from a string in Python
(26 answers)
Closed 2 years ago.
is there a function in python that does something like this:
input:
text = "s.om/e br%0oken tex!t".remove(".","/","%","0","!")
print(text)
output:
some broken text
The only thing that i know that can kinda to this is .replace("x", "") and that takes way too long to get rid of lots of different charicters. Thanks in advance.
Use regex module re to replace them all. The [] means any character in it :
text = re.sub("[./%0!]", "", "s.om/e br%0oken tex!t")
There is a module named re which is used in Regular expressions. You can use its sub function to replace or substitute characters from a string. Then you can try like this:
from re import sub
text = sub("[./%0!]","","The string")
print(text)
Regex details: Character class of . / % 0 ! if these are found in string replace them with a blank string and later print the text variable.
You might use str.maketrans combined with .translate; example:
t = str.maketrans("","","./%0!")
text = "s.om/e br%0oken tex!t"
cleantext = text.translate(t)
print(cleantext) # print(cleantext)
maketrans accept 3 arguments, every n-th character from first will be replaced with n-th character from second, all characters present in third will be jettisoned. In this case we only want to jettison so 1st and 2nd arguments are empty strs.
Alternatively you might use comprehension as follows:
text = "s.om/e br%0oken tex!t"
cleantext = ''.join(i for i in text if i not in "./%0!")
print(cleantext) # some broken text

What's the code if we want to trim the string [duplicate]

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.

.replace() in a string not replacing values [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 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.

Categories