tags:

views:

393

answers:

4
BASE_URL = 'http://foobar.com?foo=%s'

variable = 'bar'

final_url = BASE_URL % (variable)

I get this 'http://foobar.com?foo=bar' # It ignores the inside string.

But i wanted something like this 'http://foobar.com?foo='bar''

Thanks for the answer.

Can you help me out with almost the same problem:

lst = ['foo', 'bar', 'foo bar']

[str(l) for l in lst if ' ' in l]

I get ['foo bar'] but i wanted it like [''foo bar'']

Thanks in advance.

+7  A: 

Change your BASE_URL to either

BASE_URL = "http://foobar.com?foo='%s'"

or

BASE_URL = 'http://foobar.com?foo=\'%s\''
Joachim Sauer
+6  A: 

If you're working with URL parameters, it's probably safer to use urllib.urlencode:

import urllib

BASE_URL = 'http://foobar.com/?%s'
print BASE_URL % urllib.urlencode({
   'foo': 'bar',   
})

Regarding the quotes: Why do you explicitly want them? Normally your HTTP-wrapper would handle all that for you.

Regarding your 2nd question: If you absolutely also want to have the quotes in there, you still have to either escape them when appending the contained string, or (probably the safer way of doing it) would be using repr(...)

lst = ['foo', 'bar', 'foo bar']
lst2 = []

for l in lst:
    if ' ' in l:
        lst2.append(repr(l))
Horst Gutmann
+3  A: 

It seems, you are a bit confused about how string literals work.

When you say s = 'this is a string', you are assigning a string to a variable. What string? Well, a string literal that you hardcoded in your program.

Python uses the apostrophes to indicate start and end of a string literal - with anything inside being the contents of the string.

This is probably one of the first hard problems for beginners in programming: There is a difference between what you write in your programs source code and what actually happens at runtime. You might want to work through a couple of tutorials (I hear "Dive into Python" is pretty good).

Daren Thomas
Thanks for your suggestions.
aatifh
+1  A: 

If you want single quotes to appear in URL you can use

BASE_URL = 'http://foobar.com?foo=%s'
variable  = "'bar'"
final_url = BASE_URL % (variable)

But this variant is quite insecure, if variable is coming from somewhere (like user input).

Glorphindale