0

How to add commas at required positions in the given string in Python? In my case, the positions are not fixed.

Example: My requirement is to add the commas after 5th, 8th, 11th, 13th in an input string = "hello Python program"

My expected output would be: hello, Py,tho,n p,rogram

Is there any simplest way to achieve this in Python?

Actually I need to apply a comma on 590 positions in my file record and then process it.

2

3 Answers 3

3

Strings are immutable in python, so if you're going to perform modifications on the string, it would be more efficient to convert the string to a list first. You can then call str.join on the string once you're done.

string = list("hello Python program") # somewhat counterintuitive a name

for i, j in enumerate([5, 8, 11, 13]):
     string.insert(i + j, ',')

print(''.join(string))
'hello, Py,tho,n ,program'
Sign up to request clarification or add additional context in comments.

1 Comment

Dear cᴏʟᴅsᴘᴇᴇᴅ, it works perfectly for me. Thanks for help. :-)
1
>>> string = "hello Python program"
>>> commas = [5, 8, 11, 13]

One way (probably the most efficient):

>>> ','.join(string[i:j] for i, j in zip([None] + commas, commas + [None]))
'hello, Py,tho,n ,program'

Another (for this one, commas should be a set for efficiency):

>>> ''.join(c + ',' * (i in commas) for i, c in enumerate(string, 1))
'hello, Py,tho,n ,program'

Another:

>>> a = list(string)
>>> for i in reversed(commas):
        a.insert(i, ',')
>>> ''.join(a)
'hello, Py,tho,n ,program'

5 Comments

I like your 2nd and 3rd options
Possibly, yes, but I am a fan of aesthetics as much as performance ;-)
@cᴏʟᴅsᴘᴇᴇᴅ Hmm, I do like it for aesthetics as well. I think it's more straight-forward than our others. Going character by character or inserting backwards or adding an enumeration counter to the indexes all seem somewhat indirect.
Hi, facing some issue with output now. I am reading a file with is of 2199 length and trying to place commas at required positions. in an output I am getting like below, commas are coming into next line. This is happening for few records. Ex: 000XXXXXX,062,035,00,00 <=== First line ,000C160YYYYY,086,047,00, <=== next line, Code is for line in file: string=list(line) commas=[15,18,21,23,25] for i in reversed(commas): string.insert(i, ',') result=''.join(string) outfile.write(result)
@Sekhar Then your lines probably include the newline character at the end and you're putting a comma behind that.
0

Use this function:

def insertc(index,s,c):
    return s[:index]+c+s[index:]
s='hello Python program'
j=0
for i in [5,8,11,13]:
    s=insertc(i+j,s,',')
    j+=1
print(s)

1 Comment

Well it works now, but it was wrong before. Note that your answer is very similar to my answer, only more inefficient.

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.