在其他中添加字符串

2024-09-28 16:59:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似script = "C:\Users\dell\byteyears.py"的字符串。我想把字符串"Python27\"放在字符串之间,就像script = "C:\Users\dell\Python27\byteyears.py。我之所以需要它是因为构建脚本在windows上没有正确运行。不管怎样,我怎样才能及时实现这个愿望呢?你知道吗

编辑:我不会打印任何东西。字符串存储在构建脚本的脚本变量上

  script = convert_path(script)

我应该放些东西来转换它,比如

  script = convert_path(script.something("Python27/"))

问题是something应该是什么。你知道吗


Tags: path字符串py脚本编辑convertwindowsscript
3条回答

os.path是处理路径的最佳方法,在Python中也可以使用正斜杠。你知道吗

In [714]: script = r"C:/Users/dell/byteyears.py"
In [715]: head, tail = os.path.split(script)
In [716]: os.path.join(head, 'Python27', tail)
Out[716]: 'C:/Users/dell/Python27/byteyears.py'

在模块中。你知道吗

import os
script = r"C:/Users/dell/byteyears.py"
head, tail = os.path.split(script)
newpath = os.path.join(head, 'Python27', tail)
print newpath

给予

'C:/Users/dell/Python27/byteyears.py'

在内部,Python对斜杠一般是不可知的,所以使用前斜杠“/”,因为它们看起来更漂亮,而且不用逃避。你知道吗

尝试:

from os.path import abspath
script = "C:\\Users\\dell\\byteyears.py"
script = abspath(script.replace('dell\\', 'dell\\Python27\\'))

注意:在处理字符串时,千万不要忘记转义!你知道吗

如果您正在混合/和\则最好使用abspath()将其更正为您的平台!你知道吗


其他方式:

print "C:\\Users\\dell\\%s\\byteyears.py" % "Python27"

或者,如果希望路径更具动态性,可以通过这种方式传递空字符串:

print "C:\\Users\\dell%s\\byeyears.py" % "\\Python27"

也可以:

x = "C:\\Users\\dell%s\\byeyears.py"
print x
x = x % "\\Python27"
print x 
import os
os.path.join(script[:script.rfind('\\')],'Python27',script[script.rfind('\\'):])

相关问题 更多 >