0

Im looking to replace the first "/" in a string and the following works. Python3

>>> u'/test/test.json'.replace('/', '', 1)
'test/test.json'

However I do sometimes come across the following strings, where a "/" character exists but not as the first character. I only ever want to remove that character if it appears as the first character and only the first occurrence also.

>>> u'test/test.json'.replace('/', '', 1)
'testtest.json'

So test/test.json should remain test/test.json

4 Answers 4

3

There is an lstrip method just for that:

str.lstrip([chars])

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed.

'/test/test.json'.lstrip('/')

Ouput:

'test/test.json'
Sign up to request clarification or add additional context in comments.

4 Comments

This is not correct. What about "//test/test.json"? Only the first / occurrence should be removed
It would also return 'test/test.json', how would that be a problem?
yes this is very elegant thanks. works perfectly. forgot about lstrip.
The user only wants to remove the very first occurrence, as specified in the question. Anyway, this method of course covers most cases and it's a great answer!
1

Here is a possible solution (s is your string):

s = s[1:] if s[0] == '/' else s

For example:

s = 'test/test.json'
print(s[1:] if s[0] == '/' else s) # 'test/test.json'


s = '/test/test.json'
print(s[1:] if s[0] == '/' else s) # 'test/test.json'

Comments

1

You can create a simple function, which takes a string and when the first character of it is a string, it will remove it and return a proper value. If there will be no slash at the beginning, it will return a given string.

def replace_slash(string):
    if string[0] == '/':
        return string[1:]
    else:
        return string

Comments

0

You can remove the first desired character by writing a condition for that

path = u'/test/test.json'
path = path[1:] if (path[0]=='/') else path

print(path)

Thank you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.