Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
re.split although pyparsing looks interesting (note: Not Available) solution in Clear category for Backward Each Word by seflaherty
import re
def backward_string_by_word(text: str) -> str:
"""Reverse every word in the given string while keeping its position.
Args:
text (str): The given text
Returns:
str: The given text, reversed by word.
"""
re_splitter = re.split(r"(\s+)", text)
return "".join(str(i[::-1]) for i in re_splitter)
if __name__ == '__main__':
print("Example:")
print(backward_string_by_word("They say 'Ni!' to the old woman"))
# These "asserts" are used for self-checking and not for an auto-testing
assert backward_string_by_word('') == ''
assert backward_string_by_word('world') == 'dlrow'
assert backward_string_by_word('hello world') == 'olleh dlrow'
assert backward_string_by_word('hello world') == 'olleh dlrow'
assert backward_string_by_word('welcome to a game') == 'emoclew ot a emag'
print("Coding complete? Click 'Check' to earn cool rewards!")
Aug. 23, 2021