diff --git a/DIRECTORY.md b/DIRECTORY.md index f0a34a553946..6a536d3fd640 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -424,6 +424,9 @@ * [Resonant Frequency](electronics/resonant_frequency.py) * [Wheatstone Bridge](electronics/wheatstone_bridge.py) +## File Handling + * [Read File](file_handling/read_file.py) + ## File Transfer * [Receive File](file_transfer/receive_file.py) * [Send File](file_transfer/send_file.py) @@ -1314,6 +1317,7 @@ * [Prefix Function](strings/prefix_function.py) * [Rabin Karp](strings/rabin_karp.py) * [Remove Duplicate](strings/remove_duplicate.py) + * [Replace](strings/replace.py) * [Reverse Letters](strings/reverse_letters.py) * [Reverse Words](strings/reverse_words.py) * [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py) diff --git a/file_handling/read_file.py b/file_handling/read_file.py new file mode 100644 index 000000000000..3a2aeec47883 --- /dev/null +++ b/file_handling/read_file.py @@ -0,0 +1,18 @@ +# Relative path +def read_file(): + fp = open(r"test_file.txt", "r") + # read file + text = fp.read() + # Closing the file after reading + fp.close() + """ + >>> read_file() + >>> print("Hello World!") + """ + return text + + +if __name__ == __main__: + from doctest import testmod + + testmod() diff --git a/file_handling/test_file.txt b/file_handling/test_file.txt new file mode 100644 index 000000000000..980a0d5f19a6 --- /dev/null +++ b/file_handling/test_file.txt @@ -0,0 +1 @@ +Hello World! diff --git a/strings/replace.py b/strings/replace.py new file mode 100644 index 000000000000..16ef7cbba420 --- /dev/null +++ b/strings/replace.py @@ -0,0 +1,25 @@ +def string_replace( + text: str, input_string: str, replace_with_string: str, occurrence: int +) -> str: + """ + https://docs.python.org/3/library/stdtypes.html#str.replace + The replace() method replaces a specified string with another specified string. + The occurrence parameter can be skipped in order to consider all text. + Note: input and replace_with strings are case-sensitive. + >>> text = "One Two Two Three Four Five" + >>> string_val = string_replace(text, "Two", "Seven", 1) + >>> print(string_val) + One Seven Two Three Four Five + + >>> text = "In the morning, the cat is running behind the mouse." + >>> string_val = string_replace(text, "the", "a", 10) + >>> print(string_val) + In a morning, a cat is running behind a mouse. + """ + return text.replace(input_string, replace_with_string, occurrence) + + +if __name__ == "__main__": + from doctest import testmod + + testmod()