0

I have a string:

"|Antigua|and|Barbuda|19|0|2|0|0|17|1|194|20|40|408|North|America|"

And I need to change it to:

"|Antigua and Barbuda|19|0|2|0|0|17|1|194|20|40|408|North America|"

How can I do that to multiple lines?

2 Answers2

2
str = 'A.b 1.2.3 c.D'
new_str = ''
i = 0  # Keep track of where we are in the string

while i < len(str) - 2:  # Don't look past the end of the string

    # Do the next 3 characters follow the rule?
    if str[i].isalpha() and str[i + 1] == '.' and str[i + 2].isalpha():
        new_str += str[i:i + 3]
        i = i + 3

    # The next 3 characters don't follow the rule, so just take this one
    else: 
        new_str += str[i]
        i += 1

new_str += str[i:len(str)]  # Add on whatever we didn't get in the loop

print(new_str)
Josh Clark
  • 964
  • 1
  • 9
  • 17
1

This answers the edited version.

s1 = "|Antigua|and|Barbuda|19|0|2|0|0|17|1|194|20|40|408|North|America|"
s2 = "|Gulf|of|Mexico|19|0|2|0|0|17|1|194|20|40|408|North|America|"
s3 = "|Yucatan|Peninsula|19|0|2|0|0|17|1|194|20|40|408|North|America|"

s4 = "|Antigua|and|Barbuda|19|0|2|0|0|17|1|194|20|40|408|North|America|"
s5 = "|Gulf|of|Mexico|19|0|2|0|0|17|1|194|20|40|408|North|America|"
s6 = "|Yucatan|Peninsula|19|0|2|0|0|17|1|194|20|40|408|North|America|"

s_list = [s1, s2, s3]
s_list_2 = [s4, s5, s6]

def len_till_num(*args):
    for arg in args:  # for each list
        for a in arg:  # for each element in list
            i = 0  # set original index position
            while i < len(a) - 2:  # taken from other answer, not to go pass string len
                if a[i].isnumeric():  # check if current index is numeric
                    bad_str = a[1:i - 1]  # if so, assign slice and strip outside '|'s
                    good_char = bad_str.replace('|', ' ')  # assign replacement char
                    a = a.replace(bad_str, good_char)  # replace each element slice
                    i += 1  # reset original index position
                    print(a)
                    break
                else:
                    i += 1  # keep resetting original index position


len_till_num(s_list, s_list_2)

Result:

|Antigua and Barbuda|19|0|2|0|0|17|1|194|20|40|408|North|America|
|Gulf of Mexico|19|0|2|0|0|17|1|194|20|40|408|North|America|
|Yucatan Peninsula|19|0|2|0|0|17|1|194|20|40|408|North|America|
|Antigua and Barbuda|19|0|2|0|0|17|1|194|20|40|408|North|America|
|Gulf of Mexico|19|0|2|0|0|17|1|194|20|40|408|North|America|
|Yucatan Peninsula|19|0|2|0|0|17|1|194|20|40|408|North|America|

Process finished with exit code 0
Luck Box
  • 90
  • 1
  • 13