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'
Answer from Thierry Lathuille on Stack OverflowThere 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'
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'
regex - Replace first occurrence of string in Python - Stack Overflow
Python Replace String in json output
python - Replace all occurrences of a string in JSON object regardless of key - Stack Overflow
python - replacing only the first occurance of a character in string - Stack Overflow
string replace() function perfectly solves this problem:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'
Use re.sub directly, this allows you to specify a count:
regex.sub('', url, 1)
(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)
As mentioned in the comments, obj is a dict. One way to replace N/A with Not Applicable regardless of location is to convert it to a string, use string.replace and convert it back to dict for further processing
import json
#Original dict with N/A
obj = {'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': None, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}
#Convert to string and replace
obj_str = json.dumps(obj).replace('N/A', 'Not Applicable')
#Get obj back with replacement
obj = json.loads(obj_str)
Although @Devesh Kumar Singh's answer works with the sample json data in your question, converting the whole thing to a string, and then doing a wholesale bulk replace of the substring seems possibly error-prone because potentially it might change it in portions other than only in the values associated with dictionary keys.
To avoid that I would suggest using the following, which is more selective even though it takes a few more lines of code:
import json
def replace_NA(obj):
def decode_dict(a_dict):
for key, value in a_dict.items():
try:
a_dict[key] = value.replace('N/A', 'Not Applicable')
except AttributeError:
pass
return a_dict
return json.loads(json.dumps(obj), object_hook=decode_dict)
obj = {'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': None, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}
obj = replace_NA(obj)
The replace function by default is replacing all the occurrences of 1 in the string. You can limit this using the correct syntax as below
Syntax
string.replace(oldvalue, newvalue, count)
If you want only the first occurrence to get replaced you should use
s=s.replace(s[0],'9',1)
As stated in the docs:
str.replace(old, new[, count]) - Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
You don't specify count, so it replace all occurrences of s[0] - in this case '1'. In this particular case you can do
s = '12:15:45'
s = s.replace(s[0],'9',1)
print(s)
but it will not work always - e.g. if you want to replace only s[3]
text = text.replace("very", "not very", 1)
>>> help(str.replace)
Help on method_descriptor:
replace(...)
S.replace (old, new[, count]) -> string
Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
text = text.replace("very", "not very", 1)
The third parameter is the maximum number of occurrences that you want to replace.
From the documentation for Python:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
There's json module in python's standard library, it'll be much more error proof to use it rather than replacing strings.
To load json file:
import json
with open("add.json", "r") as fout2:
json_data = json.load(fout2)
for change in json_data["Changes"]:
# strip the contents of trailing white spaces (new line)
change["Name"] = change["Name"].strip()
# dump json to another file
with open("out.json", "w") as fout:
fout.write(json.dumps(json_data))
I guess you got the idea. json module will take care that your json data are not corrupted (or at least it'll fail with exception when that occurs).
just open that file as normal text file and replace the string you want to
with open('file.json', 'r+') as file:
content = file.read()
file.seek(0)
content.replace('string_replaced', 'new_string')
file.write(content)
Since you want to replace the string everywhere, it doesn't matter whether data is json or not
I would do a regex replacement on the following pattern:
@(@*)
And then just replace with the first capture group, which is all continous @ symbols, minus one.
This should capture every @ occurring at the start of each word, be that word at the beginning, middle, or end of the string.
inp = "hello @jon i am @@here or @@@there and want some@thing in '@here"
out = re.sub(r"@(@*)", '\\1', inp)
print(out)
This prints:
hello jon i am @here or @@there and want something in 'here
How about using replace('@', '', 1) in a generator expression?
string = 'hello @jon i am @@here or @@@there and want some@thing in "@here"'
result = ' '.join(s.replace('@', '', 1) for s in string.split(' '))
# output: hello jon i am @here or @@there and want something in "here"
The int value of 1 is the optional count argument.
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.