Search code examples
pythonreplaceenumerate

How to join counts from enumerate() in python?


How can I join double/triple/etc.-digit counts from enumerate() to form a single string? I want to iterate through a list of US 5-digit zipcodes in order that a new list is formed containing a reference url rewritten with each zipcode in the list:

# "70048" is the original zip
ref_url = "https://data.census.gov/cedsci/table?q=70048&tid=ACSDP5Y2020.DP05" 
indices = []
zip_list = # A list of zipcodes

for c, v in enumerate(ref_url):
    if v.isdigit():
        index = ''.join(str(c))
        indices += index
        if len(indices) == 5:
            break

indices would allow me to then .replace the exact spot (the old zipcode) I need with the next zip by doing ref_url.replace(ref_url[indices[0]]:ref_url[indices[-1]], zip) (with a separate loop). Why won't .join(c) lead to multi-digit c's joining to get a proper index?


Solution

  • A straightforward way to find the zip and replace it with each of multiple other zips would be to use re.search() and the span() method of the match object it returns:

    ref_url = "https://data.census.gov/cedsci/table?q=70048&tid=ACSDP5Y2020.DP05"
    import re
    m = re.search(r'q=\d{5}', ref_url)
    zip_list = ['12345','98765', '10101', '98989'] # A list of zipcodes
    pref, suff = ref_url[:m.span()[0] + len('q=')], ref_url[m.span()[1]:]
    for z in zip_list:
        print(pref + z + suff)
    

    Output:

    https://data.census.gov/cedsci/table?q=12345&tid=ACSDP5Y2020.DP05
    https://data.census.gov/cedsci/table?q=98765&tid=ACSDP5Y2020.DP05
    https://data.census.gov/cedsci/table?q=10101&tid=ACSDP5Y2020.DP05
    https://data.census.gov/cedsci/table?q=98989&tid=ACSDP5Y2020.DP05
    

    Alternatively, a light-touch rewrite of the code in your question to get the desired behavior is:

    ref_url = "https://data.census.gov/cedsci/table?q=70048&tid=ACSDP5Y2020.DP05" 
    indices = []
    for c, v in enumerate(ref_url):
        if v.isdigit():
            indices += [c]
            if len(indices) == 5:
                break
    zip_list = ['12345','98765', '10101', '98989'] # A list of zipcodes
    pref, suff = ref_url[:indices[0]], ref_url[indices[-1]:]
    for z in zip_list:
        print(pref + z + suff)