[Python3] Be careful with removing character strings (strip, lstrip, rstrip)

Removing strings using strip

Introduction contents

  1. When assigning to a variable
  2. String order

1. When assigning to a variable

There are the following operations to remove the character string that is python.

- strip </ b>: Returns a copy with the beginning and end of the string removed - lstrip </ b>: Returns a copy with the first character of the string removed - rstrip </ b>: Returns a copy of the string with the last character removed

The important part is " Return a copy </ b>". Note that the result differs depending on whether the copy is printed as it is or if it is assigned to a variable and then output.

strip Returns a copy with the beginning and end of the string removed

#Output as it is
a="abcdaeadcba"
print(a.strip("a"))
##output
### "bcdaeadcb"

#Substitute and then output
b="abcdedcba"
bs=b.strip("a")
print(bs)
##output
### "bcdedcb"

lstrip Returns a copy with the first character of the string removed

#Output as it is
a="abcdaeadcba"
print(a.lstrip("a"))
##output
### "bcdaeadcba"

#Substitute and then output
b="abcdedcba"
bs=b.lstrip("a")
print(bs)
##output
### "bcdedcb"

rstrip Returns a copy with the last character of the string removed

#Output as it is
a="abcdedcba"
print(a.rstrip("a"))
##output
### "bcdaeadcba"

#Substitute and then output
b="abcdedcba"
bs=b.rstrip("a")
print(bs)
##output
### "bcdedcb"

2. String order

To remove anything other than "example" from the character string "www.example.com", you can write it as follows.

#pattern 1
print('www.example.com'.strip('www.').strip(".com"))
##output
### "example"

#Pattern 2
print('www.example.com'.strip('cmowz.'))
##output
### "example"

When the character string to be removed by strip is specified, the argument is treated as " character string set </ b>". Therefore, in pattern 2, the six types of character strings "cmowz." Included in "www.example.com" are removed.

reference

https://docs.python.org/ja/3/library/stdtypes.html?highlight=strip

Recommended Posts