简体   繁体   English

字符串连接发生在python的下一行

[英]String concatenation takes place on the next line in python

Python has a simple concatenation using the + operator. Python使用+运算符进行了简单的串联。 But I am observing something unusual. 但我观察到一些异常情况。

I tried : 我试过了 :

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

Where path is a staring variable I want to concatenate. 我想连接path的起始变量。

print final_path

gives me: 给我:

/home/user/path
/output

Instead of /home/user/path/output 代替/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. 但它不起作用。

From the looks of your code, it may be the variable path that is the problem. 从代码的外观来看,可能是问题所在的变量path Check to see if path has a new line at the end. 检查path的末尾是否有新行。 Escape characters start with a backslash \\ and not a forward slash / . 转义字符以反斜杠\\而不是正斜杠/开头。

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. 如果以回车符('\\ n')结尾,则可以解释为什么字符串变量final_path会打印在两行上。

Regards. 问候。

This happens when path is from another file for example a .txt where you are importing the data. 当路径来自另一个文件(例如您要导入数据的.txt)时,就会发生这种情况。 I solved this by adding path.strip() which removes whitespaces before the str and after for the newline which is being generated. 我通过添加path.strip()解决了此问题,该方法删除了在生成的换行符str之前和之后的空格。 Just add .strip() to your variable. 只需将.strip()添加到变量中即可。

正如胜利者所说,您的路径变量在末尾隐式添加了“ \\ n”,因此您可以采取以下技巧来解决该问题:

final_path = '/home/user/' + path.strip('\n') + '/output'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM