4

Python has a simple concatenation using the + operator. But I am observing something unusual.

I tried :

final_path = '/home/user/' + path + '/output'

Where path is a staring variable I want to concatenate.

print final_path

gives me:

/home/user/path
/output

Instead of /home/user/path/output

Why is going to the next line. Is the forward slash causing the issue. I tried using the escape character as well. but It does not work.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
john
  • 335
  • 3
  • 12
  • Possible duplicate of [constructing absolute path with os.path.join()](https://stackoverflow.com/questions/17429044/constructing-absolute-path-with-os-path-join) – OneCricketeer Jun 12 '17 at 22:21
  • 1
    tl;dr `os.path.join(os.sep, 'home', 'user', path, 'output')` – OneCricketeer Jun 12 '17 at 22:23
  • If you're getting `path` from a file, that's your problem. Each line in the file includes the newline character. Just use `path.strip()`. – zondo Jun 12 '17 at 22:31

4 Answers4

4

From the looks of your code, it may be the variable path that is the problem. Check to see if path has a new line at the end. Escape characters start with a backslash \ and not a forward slash /.

victor
  • 1,573
  • 11
  • 23
  • I had another variable and there was a newline char "hidden", so your answer got me right, time saver! – Timo Jan 07 '21 at 19:18
1

As victor said, your path variable has '\n' added at the end implicitly, so you can do such a trick to overcome the problem:

final_path = '/home/user/' + path.strip('\n') + '/output'
Fioletibiel
  • 121
  • 1
  • 3
0

maybe it depends on which string is contained in the variable path. If it ends with a carriage return ('\n'), this could explain why string variable final_path is printed on 2 lines.

Regards.

TC29
  • 1
  • 2
0

This happens when path is from another file for example a .txt where you are importing the data. I solved this by adding path.strip() which removes whitespaces before the str and after for the newline which is being generated. Just add .strip() to your variable.

Darkoder
  • 25
  • 8