2

I have a list of strings: ['John','William','Ken','Rogers']. I need to prepend "Corp\" to each element in the list so that the final list looks like this:

['Corp\John','Corp\William','Corp\Ken','Corp\Rogers']

I tried the following:

 s=['John','William','Ken','Rogers']
 users=['Corp\\' + m for m in s]
 print(users)

The output gives me

 ['Corp\\John','Corp\\William','Corp\\Ken','Corp\\Rogers']

If I try users=['Corp\' + m for m in s] I get an obvious error:

"StringError EOL while scanning string literal"

I would need each element in the exact form 'Corp\name', as this needs to be used in a for loop to validate users who are eligible to login.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
  • You need to escape the backslash. Replace one backslash with two. – user3030010 Dec 06 '16 at 21:03
  • Just `print(*users)`. The `\\` is added due to `list`s calling the object's `__repr__`. – Dimitris Fasarakis Hilliard Dec 06 '16 at 21:10
  • the output you see is the representation (`repr`) of the list object (which can be used with `eval` to give you the list in python). But the actual value of each string is `'Corp\*'`. – sirfz Dec 06 '16 at 21:11
  • @JimFasarakis-Hilliard While I agree that technically this is a dupe, is it fair to think that without an understanding of `__repr__` vs `__str__` that a new user would arrive at that question based on this information? – Nathaniel Ford Dec 06 '16 at 21:17
  • @NathanielFord maybe but, I've answered a similar question 2 times already (yes, shame on me :-), you can tell OP that printing items directly will lead to the behavior they want but that doesn't answer *why* that happens. I think linking to the canonical on why this is is the best course of action. – Dimitris Fasarakis Hilliard Dec 06 '16 at 21:21
  • 1
    @JimFasarakis-Hilliard Fair enough; that's why I went and found a link to S.O. documentation as well. Cheers! – Nathaniel Ford Dec 06 '16 at 21:23
  • @user3030010 if one of the answers have answered your question correctly, you can mark it as accepted by clicking on the check mark underneath it's score. That's how we indicate to the community what worked :-) – Dimitris Fasarakis Hilliard Dec 06 '16 at 21:25

1 Answers1

4

This may be a problem with how you're 'outputting' the list. Using the REPL:

>>> lsa = ["Corp\{}".format(item) for item in ls]
>>> print(lsa)
['Corp\\Jenna', 'Corp\\Wilma', 'Corp\\Katie', 'Corp\\Rebecca']
>>> for i in lsa:
...     print(i)
... 
Corp\Jenna
Corp\Wilma
Corp\Katie
Corp\Rebecca

As you can see, in the first print, that prints the full list, we see two slashes. This is because Python is saying that the second slash is escaped. In the second print, inside a for loop, we see that there is only one slash, because we are printing each item individually and the escape string is applied, yielding only a single slash.

Graham
  • 7,431
  • 18
  • 59
  • 84
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102