john
john

Reputation: 335

String concatenation takes place on the next line in python

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.

Upvotes: 4

Views: 7768

Answers (4)

Fioletibiel
Fioletibiel

Reputation: 131

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'

Upvotes: 1

Darkoder
Darkoder

Reputation: 53

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.

Upvotes: 0

TC29
TC29

Reputation: 1

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.

Upvotes: 0

victor
victor

Reputation: 1644

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

Upvotes: 4

Related Questions