Home > Software engineering >  symbol text string
symbol text string

Time:10-20

Python. Need to place the symbol (suppose "@") BEFORE every third comma in the text. For example:

text = "Reading practice to help you understand simple texts and find specific information in everyday material. Texts include emails, invitations, personal messages, tips, notices and signs. Texts include articles, reports, messages, short stories and reviews."

That should start, I guess, to divide on comas:

st_text = text.split(",") 

Is that right? then to add certain symbol after every three got splited lines Something like that?? -

print('@'.join(st_text[i:i   3] for i in range(0, len(st_tex), 3)))

But smth going wrong..

As the result must be:

"Reading practice to help you understand simple texts and find specific information in everyday material. Texts include emails, invitations, personal messages@, tips, notices and signs. Texts include articles, reports@, messages, short stories and reviews."

CodePudding user response:

This code looks if there are three or more commas in the text. If it is, it splits the text into 4 parts, then concats the 3 first parts and adds an @ before the third comma and redo the same process with the remaining text (4th part):

text = "Reading practice to help you understand simple texts and find specific information in everyday material. Texts include emails, invitations, personal messages, tips, notices and signs. Texts include articles, reports, messages, short stories and reviews."
result = ''
while len(splitted := text.split(',', 3)) == 4:
    result  = splitted[0]   ','   splitted[1]   ','   splitted[2]   '@,'
    text = splitted[3]
result  = text
result == "Reading practice to help you understand simple texts and find specific information in everyday material. Texts include emails, invitations, personal messages@, tips, notices and signs. Texts include articles, reports@, messages, short stories and reviews."
>> True

CodePudding user response:

Something like that:

print('@,'.join([str(','.join(st_text[i:i   3])) for i in range(0, len(st_text), 3)]))
  • Related