-1

I was trying to extract the state name from the string 'Rhode Island[edit]'.

When I tried .split('[[]').str[0], I was given the correct result 'Rhode Island'. However, when I tried .rstrip('[edit]'), I was given the wrong result 'Rhode Islan'.

I got confused why the character 'd' before the left bracket was also removed when I used rstrip function.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Puzhou
  • 3
  • 2
  • 2
    The parameter to `rstrip()` is "*a string specifying the set of characters to be removed.*". Read the documentation: https://docs.python.org/3/library/stdtypes.html?highlight=rstrip#str.rstrip – cdarke Nov 17 '16 at 06:41
  • `'Rhode Island[edit]'.split('[[]').str[0]` is going to produce `AttributeError`; please verify that part of your question. – Jim Stewart Nov 17 '16 at 06:42

2 Answers2

3

rstrip doesn't do what you want, it removes all characters specified from the end of the string, so it removed '[', 'e', 'd', 'i', 't', and ']'. What you want is to split on '[' then take the first element: 'Rhode Island[edit]'.split('[')[0]

yelsayed
  • 5,236
  • 3
  • 27
  • 38
1

S.rstrip([chars]) -> string or unicode

Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping

in your case the chars = ['[','e','d','i','t',']'] which contains 'd' there fore trailing string that formed by given chars is d[edit]

try regular expression

import re
re.compile(r'\[edit\]$').sub('','Rhode Island[edit]')
Mr. A
  • 1,221
  • 18
  • 28