1

I have the following string:

string1 = "1/0/1/A1,A2"
string2 = "1/1/A1,A2"
string3 = "0/A1,A2"

In the above strings I have to replace the character with zero if it does not exist. The default structure will be "number/number/number/any_character`", if any of number is missing It has to replace with zero. The answer will be as follows.

print(string1) = "1/0/1/A1,A2"
print(string2) = "1/1/0/A1,A2"
print(string3) = "0/0/0/A1,A2"
1
  • 6
    how will the code know which element is missing.... that means in string3 = "0/A1,A2" are 0 and A1 the 3rd and 4th elements Commented Jan 26, 2019 at 13:41

3 Answers 3

1

You can use str.split:

def pad_string(_input, _add='0'):
  *_vals, _str = _input.split('/')
  return '/'.join([*_vals, *([_add]*(3-len(_vals))), _str])

results = list(map(pad_string, ['1/0/1/A1,A2', '1/1/A1,A2', '0/A1,A2']))

Output:

['1/0/1/A1,A2', '1/1/0/A1,A2', '0/0/0/A1,A2']
Sign up to request clarification or add additional context in comments.

Comments

0

You can easily fill missing elements from the left:

def fillZeros(item):
    chunks = item.split('/')
    for inserts in range(0, 4 - len(chunks)):
        chunks.insert(0, '0')
    return '/'.join(chunks)

string1 = "1/0/1/A1,A2"
string2 = "1/1/A1,A2"
string3 = "0/A1,A2"


for myString in (string1, string2, string3):
    print fillZeros(myString)

Prints:

1/0/1/A1,A2
0/1/1/A1,A2
0/0/0/A1,A2

But for you string2 example you need to identify which element is missing: 1/1/A1,A2. Is the first or the third element missing ?!

4 Comments

Third element. It only validate suffix
Yes - how do you distinguish between suffix and prefix ?
Always we have to append to suffix.
Ajax1234's answer covers this :)
0

If you want to use just string manipulation and loops, try this

strings_list = []
for string in [string1, string2, string3]:     # make list containing all strings
    strings_list.append(string)

new_strings = [] # make list containing the new strings
for string in strings_list:
    if string.count("0/") + string.count("1/") == 3:
        # identify the strings not missing a number
        new_strings.append(string)
    if string.count("0/") + string.count("1/") == 2:
        # identify the strings missing 1 number
        string = string[:4] + "0/" + string[4:]
        new_strings.append(string)
    if string.count("0/") + string.count("1/") == 1:
        # identify the strings missing 2 numbers
        string = string[:2] + "0/" + string[2:]
        new_strings.append(string)
print(new_strings)

This results in ['1/0/1/A1,A2', '1/1/0/A1,A2', '0/0/A1,A2'].

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.