Python 如果路径中有空格,则检查 2 个字符串是否表示相同的路径
Python check if 2 strings represent the same path if the path has spaces
考虑以下路径,可以用以下任一方法表示:
y="/Library/Application\ Support/Logic/Sampler\ Instruments/01\ Acoustic\ Pianos/Steinway\ Grand\ Piano\ 2.exs"
x="/Library/Application Support/Logic/Sampler Instruments/01 Acoustic Pianos/Steinway Grand Piano 2.exs"
我想找到一个忽略 space 之前的 \
的匹配方法。
我试过 os.path.expanduser
但它没有给我相同的字符串,只是在 \
符号中写入的路径中添加了额外的斜杠。
os.path.expanduser(y)
'/Library/Application\ Support/Logic/Sampler\ Instruments/01\ Acoustic\ Pianos/Steinway\ Grand\ Piano\ 2.exs'
os.path.expanduser(x)
'/Library/Application Support/Logic/Sampler Instruments/01 Acoustic Pianos/Steinway Grand Piano 2.exs'
我怎样才能 return 在这两个相等的表示上为真,或者 return 相同的字符串以便我以后可以匹配它?谢谢!
我想找到一个忽略space前的\的匹配方法。
您可以简单地 .replace
\
使用
如下
y="/Library/Application\ Support/Logic/Sampler\ Instruments/01\ Acoustic\ Pianos/Steinway\ Grand\ Piano\ 2.exs"
x="/Library/Application Support/Logic/Sampler Instruments/01 Acoustic Pianos/Steinway Grand Piano 2.exs"
print(y.replace(r"\ "," ")==x.replace(r"\ "," "))
输出
True
说明:我使用所谓的原始字符串来避免需要转义\
。 \
后面没有跟 space 的将保留不变。
考虑以下路径,可以用以下任一方法表示:
y="/Library/Application\ Support/Logic/Sampler\ Instruments/01\ Acoustic\ Pianos/Steinway\ Grand\ Piano\ 2.exs"
x="/Library/Application Support/Logic/Sampler Instruments/01 Acoustic Pianos/Steinway Grand Piano 2.exs"
我想找到一个忽略 space 之前的 \
的匹配方法。
我试过 os.path.expanduser
但它没有给我相同的字符串,只是在 \
符号中写入的路径中添加了额外的斜杠。
os.path.expanduser(y)
'/Library/Application\ Support/Logic/Sampler\ Instruments/01\ Acoustic\ Pianos/Steinway\ Grand\ Piano\ 2.exs'
os.path.expanduser(x)
'/Library/Application Support/Logic/Sampler Instruments/01 Acoustic Pianos/Steinway Grand Piano 2.exs'
我怎样才能 return 在这两个相等的表示上为真,或者 return 相同的字符串以便我以后可以匹配它?谢谢!
我想找到一个忽略space前的\的匹配方法。
您可以简单地 .replace
\
使用
如下
y="/Library/Application\ Support/Logic/Sampler\ Instruments/01\ Acoustic\ Pianos/Steinway\ Grand\ Piano\ 2.exs"
x="/Library/Application Support/Logic/Sampler Instruments/01 Acoustic Pianos/Steinway Grand Piano 2.exs"
print(y.replace(r"\ "," ")==x.replace(r"\ "," "))
输出
True
说明:我使用所谓的原始字符串来避免需要转义\
。 \
后面没有跟 space 的将保留不变。