I have a string. How do I remove all text after a certain character? (In this case ...
)
The text after will ...
change so I that's why I want to remove all characters after a certain one.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
another easy way using re will be
If you want to remove everything after the last occurrence of separator in a string I find this works well:
<separator>.join(string_to_split.split(<separator>)[:-1])
For example, if
string_to_split
is a path likeroot/location/child/too_far.exe
and you only want the folder path, you can split by"/".join(string_to_split.split("/")[:-1])
and you'll getroot/location/child
Without a RE (which I assume is what you want):
or, with a RE:
Assuming your separator is '...', but it can be any string.
If the separator is not found,
head
will contain all of the original string.The partition function was added in Python 2.5.
Split on your separator at most once, and take the first piece:
You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.