【问题标题】:How to add \\ in string with python如何使用python在字符串中添加\\
【发布时间】:2017-11-24 14:21:45
【问题描述】:

我想使用 os.join.path

获取路径位置为 '\\BIWDB02\e$\research'

我试过这些方法

 import os
 a = 'BIWDB02'
 b = 'e$\research'
 c = '\\\\'
 print c
    # \\

Try-1:

x = os.path.join('\\','\\',a,b)
print x

输出:

 \BIWDB02\e$
    esearch

不知道为什么它会出现在下一行,甚至'r'都不见了。

Try-2 ,3

y = os.path.join('\\\\',a,b)
print y

z= os.path.join(c,a,b)
print z

错误:

IndexError: 字符串索引超出范围

更新:

os.path.join('\\\\\\',a,b)
#\\\BIWDB02\e$\research

使用 6-\\\\ 它给了我 3-\\ 但使用 4-\\ 它又给了我 indexError。

【问题讨论】:

  • \r 是回车符;它告诉您的终端仿真器将光标移动到行首
  • b 定义为b = r'e$\research',然后执行os.path.join(a,b)。应该够了
  • 有关原始字符串文字的更多详细信息,请参阅this question
  • 我已经更新了我的输出:开始时应该是 \\

标签: string python-2.7 path


【解决方案1】:

问题来自e$\research 中的\r\r 被称为 carriage return 并执行返回换行符。

r 添加到e$\research 以使其成为raw string literals

import os
a = 'BIWDB02'
b = r'e$\research'
c = '\\\\'
x = os.path.join(c, a, b)
print x

>>> \\BIWDB02\e$\research

【讨论】:

  • 谢谢 .. 但我需要 \\ 在字符串的开头
  • @BHappyBHarsham 我更新了我的答案。我注意到在你的更新中,你说 \\\\ 给你一个IndexError。你运行的是哪个版本的python?我在 2.7 和 3.5 中测试了我的更新,但没有收到错误
【解决方案2】:

您不必手动转义路径名。您可以将它们转换为 Python 2.x 中的原始字符串,如下所示:

"Path with lots of tricky characte\rs.\n..durr".encode('string-escape')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2015-02-01
    相关资源
    最近更新 更多