Reputation: 63
I'm attempting to remove some unwanted characters from photo URLs.
The relevant code:
for img in imgSrc:
print(img)
img.strip('US40')
print(img)
No errors thrown, but the output is the same from both print statements:
https://images-na.ssl-images-amazon.com/images/I/51uUvUZNoUL._AC_US40_.jpg
https://images-na.ssl-images-amazon.com/images/I/51uUvUZNoUL._AC_US40_.jpg
https://images-na.ssl-images-amazon.com/images/I/51GQJaFyk1L._AC_US40_.jpg
https://images-na.ssl-images-amazon.com/images/I/51GQJaFyk1L._AC_US40_.jpg
Upvotes: 0
Views: 3314
Reputation: 2762
I see two options:
1 - Using python string's replace function:
myString = myString.replace("US40","")
2- Using re (regex) library's sub (substitute) function.
import re
Mystring = re.sub("US40","",myString)
Upvotes: 0
Reputation: 186
strip only works on leading and trailing characters. You should use replace in this case
Strip: S.strip([chars]) -> str
Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.
Replace: S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
for img in imgSrc:
print(img)
img = img.replace('US40',"")
print(img)
Upvotes: 3
Reputation: 582
Strip only deletes leading and trailing characters from a string. I don't know exactly what you want to achieve, but if you're interested in deleting some part of the string throughout its full length then you can use string.replace() method and replace something to the empty string ""
.
For example, below code deletes all of the a
characters from a string:
s = 'abc12321cba'
print(s.replace('a', ''))
Output: bc12321cb
Upvotes: 0
Reputation: 24691
str.strip()
only removes characters from either end of the string. In this case, the text you want to remove is a few characters to the interior.
You can use str.replace()
with an empty string to remove any occurrences of the character, anywhere in the string. Is this what you want?
print(img)
# https://images-na.ssl-images-amazon.com/images/I/51uUvUZNoUL._AC_US40_.jpg
img = img.replace('US40', '')
print(img)
# 'https://images-na.ssl-images-amazon.com/images/I/51uUvUZNoUL._AC__.jpg'
Upvotes: 0
Reputation: 16999
Python strip is a function which returns a value which you must assign to a variable:
x = text.strip()
And as others stated in your case you must use something else for the job. So you have two issues at once.
Upvotes: 0