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.

3
  • Possible duplicate of constructing absolute path with os.path.join() Commented Jun 12, 2017 at 22:21
  • 1
    tl;dr os.path.join(os.sep, 'home', 'user', path, 'output') Commented Jun 12, 2017 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(). Commented Jun 12, 2017 at 22:31

4 Answers 4

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 /.

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

1 Comment

I had another variable and there was a newline char "hidden", so your answer got me right, time saver!
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'

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.