-2

I have a string "E001" I would like to add "\u" to the beginning of that string So the code would look something like this:

output = add_u("E001")
print(output)
--------------------------
OUTPUT: \uE001

There are difficulties with this I keep getting a Unicode error

Quinten C
  • 660
  • 1
  • 8
  • 18

2 Answers2

2

How about just:

output = "\\u" + "E001"
print(output)

Or as a function:

def add_u(string):
    return "\\u" + string

output = add_u("E001")
print(output)

Handles backslash escaping.

miike3459
  • 1,431
  • 2
  • 16
  • 32
0

Try this:

def add_u(s):
    return r'\u' + s

print(add_u('E001'))

Outputs:

\uE001
Luke DeLuccia
  • 541
  • 6
  • 16
  • This worked! What exactly does the r in front of the string mean? I have come across when I tried to solve this on my own but I find the meaning unclear. – Quinten C Jan 03 '19 at 22:24
  • The r means raw string literal. https://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-and-what-are-raw-string-literals – Luke DeLuccia Jan 03 '19 at 22:31
  • So when I add this string to a list it adds a second "\", a_list = ["\uE001"] becomes ["\\uE001"] is there any way to prevent this? I have the string in a variable if you do this literally nothing will happen but if you return a variable from a function and put that in a list then this happens – Quinten C Jan 03 '19 at 23:06
  • You're looking at the representation of the string, not at the string content. If you have `x = '\\` in your code then `x` will be a string with one character, the backslash. See the difference with `print(x, repr(x))`. – Matthias Jan 04 '19 at 08:02