Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 833587
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T04:32:30+00:00 2026-05-15T04:32:30+00:00

I’m looking for the most efficient way to add an element to a comma-separated

  • 0

I’m looking for the most efficient way to add an element to a comma-separated string while maintaining alphabetical order for the words:

For example:

string = 'Apples, Bananas, Grapes, Oranges'
subtraction = 'Bananas'
result = 'Apples, Grapes, Oranges'

Also, a way to do this but while maintaining IDs:

string = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges'
subtraction = '4:Bananas'
result = '1:Apples, 6:Grapes, 23:Oranges'

Sample code is greatly appreciated. Thank you so much.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T04:32:30+00:00Added an answer on May 15, 2026 at 4:32 am

    Ideally, something like:

    input_str = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges'
    removal_str = '4:Bananas'
    sep = ", "
    
    print sep.join(input_str.split(sep).remove(removal_str))
    

    would work. But python doesn’t return the new list from remove(), so you can’t do that all on one line, and need temporary variables etc. A similar solution that does work is:

    input_str = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges'
    removal_str = '4:Bananas'
    sep = ", "
    
    print sep.join([ i for i in input_str.split(sep) if i != removal_str ])
    

    However, to be as correct as possible, assuming you’ve no GUARANTEE that all items are valid, you’d need to verify that each item matches ALL of the specifications given to you, namely that they’re of the format number:identifier. The simplest way to do that is to use the re module to search for a specific regular expression format, return all results, and skip results that don’t match what you want. Using deliberately compact code, you get a reasonably short solution that does good validation:

    def str_to_dictlist(inp_str):
        import re
        regexp = r"(?P<id>[0-9]+):(?P<name>[a-zA-Z0-9_]+)"
        return [ x.groups() for x in re.finditer(regexp, inp_str) ]
    
    input_str = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges'
    subtraction_str = "4:Bananas"
    sep = ", "
    
    input_items = str_to_dictlist(input_str)
    removal_items = str_to_dictlist(subtraction_str)
    final_items = [ "%s:%s" % (x,y) for x,y in input_items if (x,y) not in removal_items ]
    
    print sep.join(final_items)
    

    This also has the advantage of handling multiple removals at the same time. Since the input format and removal formats are so similar, and the input format has multiple items, it makes sense that the removal format might need to support them too — or at least, that it’s useful to have that support.

    Note that doing it this way (using re to search) would make it difficult to detect items that DON’T validate though; it would just scan for anything that does. As a hack, you could count commas in the input and report a warning that something might have failed to parse:

    if items_found < (num_commas + 1):
        print warning_str
    

    This would warn about commas without spaces as well.

    To parse more complex input strings properly, you need to break it down into individual tokens, track input lines and columns as you parse, print errors for anything unexpected, and maybe even handle stuff like backtracking and graph-building for more complex inputs like source code. For that sort of stuff, look into the pyparsing module (which is a third-party download; it doesn’t come with python).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a jquery bug and I've been looking for hours now, I can't
I would like to count the length of a string with PHP. The string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
Specifically, suppose I start with the string string =hello \'i am \' me And
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.