crappy smith
crappy smith

Reputation: 53

Strip in Python

I have a question regarding strip() in Python. I am trying to strip a semi-colon from a string, I know how to do this when the semi-colon is at the end of the string, but how would I do it if it is not the last element, but say the second to last element.

eg:

1;2;3;4;\n

I would like to strip that last semi-colon.

Upvotes: 5

Views: 20303

Answers (8)

swang
swang

Reputation: 219

re.sub(r';(\W*$)', r'\1', '1;2;3;4;\n') -> '1;2;3;4\n'

Upvotes: 1

rtmh
rtmh

Reputation: 449

If you only want to use the strip function this is one method: Using slice notation, you can limit the strip() function's scope to one part of the string and append the "\n" on at the end:

# create a var for later
str = "1;2;3;4;\n"
# format and assign to newstr
newstr = str[:8].strip(';') + str[8:]

Using the rfind() method(similar to Micheal0x2a's solution) you can make the statement applicable to many strings:

# create a var for later
str = "1;2;3;4;\n"
# format and assign to newstr
newstr = str[:str.rfind(';') + 1 ].strip(';') + str[str.rfind(';') + 1:]

Upvotes: 1

mhoran_psprep
mhoran_psprep

Reputation: 181

how about replace?

string1='1;2;3;4;\n'
string2=string1.replace(";\n","\n")

Upvotes: 4

Curious
Curious

Reputation: 2971

You could split the string with semi colon and then join the non-empty parts back again using ; as separator

parts = '1;2;3;4;\n'.split(';')
non_empty_parts = []
for s in parts:
    if s.strip() != "": non_empty_parts.append(s.strip())
print "".join(non_empty_parts, ';')

Upvotes: 1

Michael0x2a
Michael0x2a

Reputation: 64058

Try this:

def remove_last(string):
    index = string.rfind(';')
    if index == -1:
        # Semi-colon doesn't exist
        return string
    return string[:index] + string[index+1:]

This should be able to remove the last semicolon of the line, regardless of what characters come after it.

>>> remove_last('Test')
'Test'
>>> remove_last('Test;abc')
'Testabc'
>>> remove_last(';test;abc;foobar;\n')
';test;abc;foobar\n'
>>> remove_last(';asdf;asdf;asdf;asdf')
';asdf;asdf;asdfasdf'

The other answers provided are probably faster since they're tailored to your specific example, but this one is a bit more flexible.

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304147

>>> "".join("1;2;3;4;\n".rpartition(";")[::2])
'1;2;3;4\n'

Upvotes: 4

Ian Clelland
Ian Clelland

Reputation: 44132

>>> string = "1;2;3;4;\n"
>>> string.strip().strip(";")
"1;2;3;4"

This will first strip any leading or trailing white space, and then remove any leading or trailing semicolon.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

Strip the other characters as well.

>>> '1;2;3;4;\n'.strip('\n;')
'1;2;3;4'

Upvotes: 9

Related Questions