Python string strip function - python

Why are following code can remove '+':
a = '+'
a.strip('+')
#output: ''
a = '1+'
a.strip('+')
#output: '1'
a = '+66'
a.strip('+')
#output: '66'
But the followings can't:
a = '1+2'
a.strip('+')
#output: '1+2'
Why?

The strip() function only removes leading and trailing characters - on the outside of the string. Since in your last example the + is in the middle, it doesn't remove it. Maybe try using replace() instead:
my_str = "1+2"
new_str = my_str.replace("+", "")

strip only removes the specified heading and trailing characters the string, not in the middle.
Similarly, rstrip only removes the trailing ones.

Related

How to remove a specific character from a string

I'm trying to remove the single quotation marks from "'I'm'" to have "I'm" in the end. I tried the replace() and translate() buils-in methods but neither of them does what I want. This is what I tried
string = "'I'm'"
for ch in string:
if ch == "'" and (string[0] == ch or string[-1] == ch):
string = string.replace(ch, "")
I tried other ways but keeps on returning "Im" as output.
Your code has a few flaws:
Why are you iterating over the string if the only thing you need to check is the first and the last character?
While iterating a string you should not change it. It leads to unexpected and undesired consequences.
Your Boolean logic seems odd.
You are replacing all of the quotes in the first loop.
What would work is this:
if string[0] == "'" and string[-1] == "'" and len(string) > 1:
string = string[1:-1]
Where you do pretty much the same checks you want but you just remove the quotations instead of alternating the inner part of the string.
You could also use string.strip("'") but it is potentially going to do more than you wish removing any number of quotes and not checking if they are paired, e.g.
"'''three-one quotes'".strip("'")
> three-one quotes
Just use strip:
print(string.strip("'"))
Otherwise try this:
if (string[0] == "'") or (string[-1] == "'"):
string = string[1:-1]
print(string)
Both codes output:
I'm
To remove leading and trailing characters from a string you will want to use the str.strip method instead:
string = "'I'm'"
string = string.strip("'")

Turn string into a list and remove carriage returns (Python)

I have a string like this:
['过\r\n啤酒\r\n小心\r\n照顾\r\n锻炼\r\n过去\r\n忘记\r\n哭\r\n包\r\n个子\r\n瘦\r\n选择\r\n奶奶\r\n突然\r\n节目\r\n']
How do I remove all of the "\r\n", and then turn the string into a list like so:
[过, 啤酒, 小心, 照顾, 过去, etc...]
str.split removes all whitespace; this includes \r and \n:
A = ['过\r\n啤酒\r\n小心\r\n照顾\r\n锻炼\r\n过去\r\n忘记\r\n哭\r\n包\r\n个子\r\n瘦\r\n选择\r\n奶奶\r\n突然\r\n节目\r\n']
res = A[0].split()
print(res)
['过', '啤酒', '小心', '照顾', '锻炼', '过去', '忘记', '哭', '包', '个子', '瘦', '选择', '奶奶', '突然', '节目']
As described in the str.split docs:
If sep is not specified or is None, a different splitting
algorithm is applied: runs of consecutive whitespace are regarded as a
single separator, and the result will contain no empty strings at the
start or end if the string has leading or trailing whitespace.
To limit the split to \r\n you can use .splitlines():
>>> li=['过\r\n啤酒\r\n小心\r\n照顾\r\n锻炼\r\n过去\r\n忘记\r\n哭\r\n包\r\n个子\r\n瘦\r\n选择\r\n奶奶\r\n突然\r\n节目\r\n']
>>> li[0].splitlines()
['过', '啤酒', '小心', '照顾', '锻炼', '过去', '忘记', '哭', '包', '个子', '瘦', '选择', '奶奶', '突然', '节目']
Try this:
s = "['过\r\n啤酒\r\n小心\r\n照顾\r\n锻炼\r\n过去\r\n忘记\r\n哭\r\n包\r\n个子\r\n瘦\r\n选择\r\n奶奶\r\n突然\r\n节目\r\n']"
s = s.replace('\r\n', ',').replace("'", '')
print(s)
Output:
[过,啤酒,小心,照顾,锻炼,过去,忘记,哭,包,个子,瘦,选择,奶奶,突然,节目,]
This first replace replaces the \r\n and the second one replaces the single quote from the string as you expected as the output.

Python how to remove equal sign "=" in strings?

Python how to remove = in strings?
a = 'bbb=ccc'
a.rstrip('=')
# returns 'bbb=ccc'
a.rstrip('\=')
# alse returns 'bbb=ccc'
how to match = ?
You can replace it with an empty string:
a.replace("=", "")
For reference:
https://docs.python.org/3/library/stdtypes.html#str.replace
You can use the replace method (easiest):
a = 'bbb=ccc'
a.replace('=', '')
or the translate method (probably faster on large amounts of data):
a = 'bbb=ccc'
a.translate(None, '=')
or the re.sub method (most powerful, i.e. can do much more):
import re
re.sub('=', '', 'aaa=bbb')
strip removes characters from the beginning and from the end of the string!
From the documentation:
str.strip([chars])
Return a copy of the string with leading and trailing characters removed.
Since you "=" is neither at the beggining nor at the end of your string, you can't use strip for your purpose. You need to use replace.
a.replace("=", "")

Remove a set of prefix characters from string in python

I am trying to remove all the prefix "#" from the string "####b##"
Expected output is "b##" (not all the '#' but only prefix)
If there is no prefix "#", it should return the original string itself
This is the code, I am trying : (I am using python 2.X)
mylist = []
def remove(S):
mylist.append(S)
j=0
for i in range(len(S)):
if mylist[0][j]=='#':
S = S[:j] + S[j + 1:]
j+=1
return S
else:
return S
break
a = remove("####b##")
print a
Use lstrip()
Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed.
>>> "####b##".lstrip("#")
'b##'
Python 3.9
There are two new string methods, removesuffix() and removeprefix()
"HelloWorld".removesuffix("World")
Output: "Hello"
"HelloWorld".removeprefix("Hello")
Output: "World"
Before Python 3.9
Using lstrip() (See Christians answer)
Be careful using lstrip and rstrip. If you are trying just to remove the first few letters. lstrip() and rstrip() will keep removing letters until it reaches an unrecognizable one.
a = "###b##"
print(a.lstrip('###b'))
Output:
Above output is a empty string, lstrip strips off everything!
a = "###b##c"
print(a.lstrip('###b'))
Output: c
Use a regular expression
import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)
def remove(S): return S[4:] if S.startswith('####') else S
>>> remove('####b##')
'b##'
>>> remove('###b##')
'###b##'

Understanding string method strip

After initializing a variable x with the content shown in below, I applied strip with a parameter. The result of strip is unexpected. As I'm trying to strip "ios_static_analyzer/", "rity/ios_static_analyzer/" is getting striped.
Kindly help me know why is it so.
>>> print x
/Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer/
>>> print x.strip()
/Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer/
>>> print x.strip('/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer
>>> print x.strip('ios_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/secu
>>> print x.strip('analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_
>>> print x.strip('_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static
>>> print x.strip('static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/io
>>> print x.strip('_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/io
>>> print x.strip('s_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/io
>>> print x.strip('os_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/secu
Quoting from str.strip docs
Return a copy of the string with the leading and trailing characters
removed. The chars argument is a string specifying the set of
characters to be removed. If omitted or None, the chars argument
defaults to removing whitespace. The chars argument is not a prefix or
suffix; rather, all combinations of its values are stripped:
So, it removes all the characters in the parameter, from both the sides of the string.
For example,
my_str = "abcd"
print my_str.strip("da") # bc
Note: You can think of it like this, it stops removing the characters from the string when it finds a character which is not found in the input parameter string.
To actually, remove the particular string, you should use str.replace
x = "/Users/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer/"
print x.replace('analyzer/', '')
# /Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_
But replace will remove the matches everywhere,
x = "abcd1abcd2abcd"
print x.replace('abcd', '') # 12
But if you want to remove words only at the beginning and ending of the string, you can use RegEx, like this
import re
pattern = re.compile("^{0}|{0}$".format("abcd"))
x = "abcd1abcd2abcd"
print pattern.sub("", x) # 1abcd2
What you need, I think, is replace:
>>> x.replace('ios_static_analyzer/','')
'/Users/msecurity/Desktop/testspace/Hy5_Workspace/security/'
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new.
So you can replace your string with nothing and get the desired output.
Python x.strip(s) remove from the begginning or the end of the string x any character appearing in s ! So s is just a set of characters, not a string being matched for substring.
string.strip removes a set of characters given as an argument. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.
strip does not remove the string given as argument from the object; it removes the characters in the argument.
In this case, strip sees the string s_static_analyzer/ as an iterable of characters that needs to be stripped.

Categories

Resources