Reputation: 16479
I practicing interview questions from cracking the code interview.
The question is for each space (' ') replace it with '%20'. The end of the string has 2 extra spaces for each space in the string.
For example input: str = "b_g_f_ _ _ _"
(underscores represent space. Easier to represent)
output: str2 = "b%20g%20f"
Currently my output is not working properly
input: "b c "
output: "b%20c%20%20"
correct output: "b%20c"
code:
def editstr(str):
str2 = ""
length = len(str)
count = 0
while 3*count < length:
for char in str:
if ord(char) < 257 and ord(char) >= 0 and ord(char) != 32:
str2 = str2 + char
count += 1
else:
if ord(char) == 32:
str2 = str2 + ("%20")
count += 3
print str2
Upvotes: 0
Views: 1011
Reputation: 1650
more pythonic :
import urllib
urllib.quote(url.strip())
Following up the discussion above :
urllib.quote(url[:-2]+(url[-2:].strip()))
Upvotes: 0
Reputation: 14089
Is this cheating?
> import urllib
> urllib.quote("b g f ")
'b%20g%20f%20%20%20%20%20'
Thanks to @SteveJessop I finally understood the question I wasn't sure what was the right output in the example, here is my take on it using generators, maybe it is more efficient :
input = "b g f "
def generate_str(input):
new, orig = [len(input)] * 2
for i, char in enumerate(input):
if i == new:
break
if char == " ":
new -= 2
yield "%20"
else:
yield char
print ''.join(generate_str(input))
Upvotes: 3
Reputation: 85875
Maybe I am missing something but what is wrong with just doing:
>>> s = "b f g "
>>> s.strip().replace(' ','%20')
'b%20f%20g'
Rewriting behaviour that is built right into the language doesn't make you smarter, quite the opposite. Look at it this way:
Upvotes: 4
Reputation: 179602
Python strings are immutable. The extra spaces in the input string are therefore no help if you want to implement such string replacement in Python. If you want to solve a problem in Python, do it in a Pythonic way:
def editstr(s):
n = s.count(' ')
if n == 0: return s
return s[:-2*n/3].replace(' ', '%20')
This removes the "extra" spaces added at the end, and uses .replace
to do the actual string replacement.
Upvotes: 3
Reputation: 11
At the end of the input string, those spaces will not count as part of the conversion. According to ASCII, a space char ‘ ’ is number 32, but a void char, is number 0. This would help you to understand what this problem means by saying enough space at the end of the char array. Besides that, this interview question specified that you should be doing the conversion in place. So try not to create a second string for that.
Upvotes: 0