1

Set-up

I have a pandas DataFrame df.

For each row in df['district'] I create a temp string which I append to list sl1.

Subsequently, I add two strings to each temp in sl1 and append the result to a second list sl2.

I do this in the following way,

sl1 = []
for key, value in df['district'].iteritems():
    temp = "http://www.jaap.nl/huurhuizen/zuid+holland/agglomeratie+'s-gravenhage/'s-gravenhage"
    sl1.append(temp)    

sl2 = []
for link in sl1:
    x = '<a href="' + link + '">'
    sl2.append(x)     


Issue

In the second for loop, something strange occurs. In stead of obtaining an sl2 filled with rows containing,

'<a href="http://www.jaap.nl/huurhuizen/zuid+holland/agglomeratie+'s-gravenhage/'s-gravenhage">'

the rows are filled with,

'<a href="http://www.jaap.nl/huurhuizen/zuid+holland/agglomeratie+\'s-gravenhage/\'s-gravenhage">'

How come Python adds those backslashes, and more importantly:

How can I prevent/remove them?

Does it have to do with the ' in 's-gravenhage?

2
  • 3
    The backslashes are not part of the string. They're just how Python represents the fact that the apostrophe doesn't close the string. There is no reason for you to change anything here. Commented May 21, 2017 at 18:27
  • 3
    Don't confuse the representation (which has to be a valid string literal) with the value. Those backslashes are required only when re-creating the value. Commented May 21, 2017 at 18:29

1 Answer 1

2

As pointed out in comments, this is just representation of the value. Those backslashes are just escape characters for the single quote '.

If you print x or write it to a file, you'd see that the output is just fine.

temp = "http://www.jaap.nl/huurhuizen/zuid+holland/agglomeratie+'s-gravenhage/'s-gravenhage"
x = '<a href="' + temp + '">'
print(x)

This returns <a href="http://www.jaap.nl/huurhuizen/zuid+holland/agglomeratie+'s-gravenhage/'s-gravenhage"> as expected.

Sign up to request clarification or add additional context in comments.

2 Comments

I like cabbage.
@LucSpan I like how you split your questions into set-up and problem. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.