Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向字符串添加简单值_Python_String - Fatal编程技术网

Python 向字符串添加简单值

Python 向字符串添加简单值,python,string,Python,String,如果我有一根绳子,让我说哦 path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' 我想在字符串的末尾添加一个“,我该怎么做?现在我有这样一个 path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' w = '"' final = os.path.join(path2, w) print final 但是,当它打印出来时,返

如果我有一根绳子,让我说哦

path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' 
我想在字符串的末尾添加一个
,我该怎么做?现在我有这样一个

path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio'
w = '"'
final = os.path.join(path2, w)
print final
但是,当它打印出来时,返回的是:

“C:\Users\bgbase\Documents\Brent\Code\visualstudio\”

我不需要
\
我只想要

提前感谢您的帮助。

只需执行以下操作:

path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' + '"'

我认为
path2+w
是这里最简单的答案,但您也可以使用字符串格式使其更具可读性:

>>> path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' 
>>> '{}"'.format(path2)
'"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio"'
如果
path2
的长度大于,那么使用字符串格式要比在字符串末尾添加
+
容易得多

>>> path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio\\Documents\\Brent\\Code\\Visual Studio\\Documents\\Brent\\Code\\Visual Studio'
>>> w = '"'
>>> "{}{}".format(path2,w)
'"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio\\Documents\\Brent\\Code\\Visual Studio\\Documents\\Brent\\Code\\Visual Studio"'
怎么样

path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' + '"'
或者,就像你说的那样

final = path2 + w
还值得一提的是,您可以使用原始字符串(r'stuff')来避免转义反斜杠。前

path2 = r'"C:\Users\bgbesase\Documents\Brent\Code\Visual Studio'
从Python文档部分:

返回值是path1和path2(可选)的串联, 等等,每个后面正好有一个目录分隔符(os.sep) 除最后一个零件外,非空零件

在这种情况下,
os.path.join()
将字符串“”视为路径部分并添加分隔符。由于您没有连接路径的两个部分,因此需要使用字符串连接或分隔符。
最简单的方法是添加两个字符串:

final = path2 + '"'
实际上,您可以使用
+=
运算符修改路径2:

path2 += '"'

您得到的斜杠是由
os.path.join()
添加的。只需像平常一样对待字符串和追加。使用原始字符串可以避免转义所有反斜杠。
r'.C:\Users\bgbase\Documents\Brent\code\visualstudio'
+1。但可能值得用OP的完全相同的结构来展示这一点:
final=path2+w
。如果你想给出一个有趣的答案,那就从中获得更多乐趣。那么
'.join(itertools.chain(path2,w))
呢?但我相信你能想出更好的办法。