Python Forum
how to replace comma with string "and" but with conditons
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to replace comma with string "and" but with conditons
#1
Hi,

I have a text written like this :
apartments, villa, studio apartments, shops

i want to replace last comma with "and"

expected output:
apartments, villa, studio apartments and shops

how can i do this?i tried this:
m = apartments, villa, studio apartments, shops

getreplaced = m.replace(","," and ")
but dont know what to do next
Reply
#2
Split from right by comma and join by and
'and'.join(m.split(',', 1))
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
i received this result:

apartmrentsandvilla,studio apatments,shops
i used :
mc = 'and'.join(m.split(',', 1))
expected output:
apartments, villa, studio apartments and shops
Reply
#4
(Sep-17-2018, 11:09 AM)Prince_Bhatia Wrote: i received this result:

apartmrentsandvilla,studio apatments,shops
i used :
mc = 'and'.join(m.split(',', 1))
expected output:
apartments, villa, studio apartments and shops

Sorry, replace split with rsplit
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 770 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,210 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,587 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,121 Aug-19-2022, 08:07 PM
Last Post: Winfried
  Find and Replace numbers in String giddyhead 2 1,242 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  How to format Excel column with comma? dee 0 1,372 Jun-13-2022, 10:11 PM
Last Post: dee
  decimal comma DPaul 9 2,291 Feb-22-2022, 12:25 PM
Last Post: DeaD_EyE
  Replace String in multiple text-files [SOLVED] AlphaInc 5 8,150 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
  Replace String with increasing numer [SOLVED] AlphaInc 13 5,050 Aug-07-2021, 08:16 AM
Last Post: perfringo
  Adding a comma in the resulting value stsxbel 6 2,654 May-22-2021, 09:24 PM
Last Post: stsxbel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020