From 9ec2b6e28b44c4af443bbf8f424ed1de2f8eb1be Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Sat, 9 May 2015 11:28:29 -0400 Subject: [PATCH] Added python solutions to encoding spaces. --- arrays-strings/replace_char.ipynb | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/arrays-strings/replace_char.ipynb b/arrays-strings/replace_char.ipynb index 542b784..69491d8 100644 --- a/arrays-strings/replace_char.ipynb +++ b/arrays-strings/replace_char.ipynb @@ -4,12 +4,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Problem: Given a String, Replace In-Place all Spaces with '%20'\n", + "## Problem: Given a string, replace in-place all spaces with '%20'\n", "\n", "* [Clarifying Questions](#Clarifying-Questions)\n", "* [Test Cases](#Test-Cases)\n", "* [Algorithm](#Algorithm)\n", - "* [Code](#Code)" + "* [Code](#Code)\n", + "* [Pythonic-Code: Not In-Place](#Pythonic-Code:-Not-In-Place)" ] }, { @@ -106,6 +107,32 @@ "print(str2)\n", "print(str3)" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Pythonic-Code: Not In-Place\n", + "\n", + "The following code is Pythonic, but requires using additional data structures as Python strings are immutable. You could use a bytearray or a list instead of a string to simulate manipulating an array of characters." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import re\n", + "\n", + "def encode_spaces_alt(string):\n", + " return re.sub(' ', '%20', string)\n", + "\n", + "def encode_spaces_alt2(string):\n", + " return string.replace(' ', '%20')" + ] } ], "metadata": {