Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Remove Parts of string by index

Tags:

python

string

I have a string

string='texttexttextblahblah",".'

and what I want to do is cut of some of the rightmost characters by indexing and assign it to string so that string will be equal to texttexttextblahblah"

I've looked around and found how to print by indexing, but not how to reassign that actual variable to be trimmed.

like image 552
Brian Avatar asked Aug 18 '10 20:08

Brian


2 Answers

Just reassign what you printed to the variable.

>>> string='texttexttextblahblah",".'
>>> string = string[:-3]
>>> string
'texttexttextblahblah"'
>>>

Also, avoid using names of libraries or builtins (string) for variables

Unless you know exactly how many text and blah's you'll have, use .find() as Brent suggested (or .index(x), which is like find, except complains when it doesn't find x).

If you want that trailing ", just add one to the value it kicks out. (or just find the value you actually want to split at, ,)

mystr = mystr[:mystr.find('"') + 1]
like image 177
Nick T Avatar answered Nov 15 '22 18:11

Nick T


If you need something that works like a string, but is mutable you can use a bytearray

>>> s=bytearray('texttexttextblahblah",".')
>>> s[20:]=''
>>> print s
texttexttextblahblah

bytearray has all the usual string methods

like image 42
John La Rooy Avatar answered Nov 15 '22 17:11

John La Rooy