Why The Output Is Not Getting Striped Of 'the'
Solution 1:
Your input string actually starts with a space. In this case, you might want to consider using re.sub
here:
zen = re.sub(r'^\s*The\b', zenPython)
This removes an initial word The
at the start of the input, possibly preceded by any amount of whitespace, which would also be removed.
Solution 2:
.strip()
is not the right function to use for what you want to achieve. It happens to have the right result (for this specific string), but for wrong reasons. It will delete all characters from beginning and end, matching the collection provided. That means:
"ThehehxxehT".strip("The") == "xx"
For a better solution, use the re.sub
mentioned in another comment or strip it manually by length:
defremove_prefix(original, prefix):
if original.startswith(prefix):
return original[len(prefix):]
else:
return original
zen = remove_prefix(zen, "The")
In your case you'll also have to remove the initial newline in the string (your string starts with <newline>The
).
The triple quotes are to allow a multi-line string.
Solution 3:
You are doing right, but as there is leading space before The
, it is not striping as you expected. By default, strip
will remove all leading and trailing spaces.
So, you can try strip in this way,
>>>zenPython.strip().strip('The')
Output:
" Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"
Post a Comment for "Why The Output Is Not Getting Striped Of 'the'"