Reputation: 85
I am trying to scan a string and every time it reads a certain character 3 times, I would like to cut the remaining string
for example: The string "C:\Temp\Test\Documents\Test.doc" would turn into "C:\Temp\Test\"
Every time the string hits "\" 3 times it should trim the string
here is my code that I am working on
prefix = ["" for x in range(size)]
num = 0
...
...
for char in os.path.realpath(src):
for x in prefix:
x = char
if x =='\': # I get an error here
num = num + 1
if num == 3:
break
print (num)
print(prefix)
...
...
the os.path.realpath(src)
is the string with with the filepath. The "prefix" variable is the string array that I want to store the trimmed string.
Please let me know what I need to fix or if there is a simpler way to perform this.
Upvotes: 2
Views: 100
Reputation: 813
In python the backslash character is used as an escape character. If you do \n it does a newline, \t does a tab. There are many other things such as \" lets you do a quote in a string. If you want a regular backslash you should do "\\"
Upvotes: 1
Reputation: 26039
Do split
and then slice list to grab required and join
:
s = 'C:\Temp\Test\Documents\Test.doc'
print('\\'.join(s.split('\\')[:3]) + '\\')
# C:\Temp\Test\
Note that \
(backslash) is an escaping character. To specifically mean a backslash, force it to be a backslash by adding a backslash before backslash \\
, thereby removing the special meaning of backslash.
Upvotes: 2
Reputation: 421
Something like this would do..
x = "C:\Temp\Test\Documents\Test.doc"
print('\\'.join(x.split("\\")[:3])+"\\")
Upvotes: 0
Reputation: 8018
try
s = "C:\\Temp\\Test\\Documents\\Test.doc"
answer = '\\'.join(s.split('\\', 3)[:3])
Upvotes: 0