Python Forum
How to iterate over some characters in a string and the others will stay as it is. ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to iterate over some characters in a string and the others will stay as it is. ?
#5
(Jun-17-2019, 10:16 AM)noisefloor Wrote: Hi,

@sodmzs: iterating with range(len(..)) and the index over an iterable is an anti-pattern, don't do it. Python support direct iteration:

>>> one = ['one', 'o', 'n' ,'e']
>>> two = ['two', 't', 'w', 'o']
>>> for item in one:
...     for other_item in two:
...         print('{} {}'.format(item, other_item))
...
one two
one t
one w
one o
o two
o t
o w
o o
n two
n t
n w
n o
e two
e t
e w
e o
>>>
But using itertools as shown is the more elegant way anyway.

Regards, noisefloor


Thanks for your reply, but I was looking forward for the other words in the string will stay as it is same. That is in my case, the string was "one and two" Means just the "one" And "two" Will iterate and "and" Word will be in the same position. Since, I want to make it flexible so that in case I would have a string like "two and one and two" Then it can work well with this as well.
Reply


Messages In This Thread
RE: How to iterate over some characters in a string and the others will stay as it is. ? - by sodmzs - Jun-17-2019, 12:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  doing string split with 2 or more split characters Skaperen 22 2,609 Aug-13-2023, 01:57 AM
Last Post: Skaperen
  How do I check if the first X characters of a string are numbers? FirstBornAlbratross 6 1,592 Apr-12-2023, 10:39 AM
Last Post: jefsummers
Question [SOLVED] Delete specific characters from string lines EnfantNicolas 4 2,268 Oct-21-2021, 11:28 AM
Last Post: EnfantNicolas
  Make these LEDs stay on duckredbeard 5 3,011 Apr-08-2021, 10:26 PM
Last Post: duckredbeard
  Extract continuous numeric characters from a string in Python Robotguy 2 2,673 Jan-16-2021, 12:44 AM
Last Post: snippsat
Question How to make a button always stay on a point when resizing the window? _ShevaKadu 5 4,292 Nov-04-2020, 03:59 PM
Last Post: deanhystad
  Python win32api keybd_event: How do I input a string of characters? JaneTan 3 3,875 Oct-19-2020, 04:16 AM
Last Post: deanhystad
  How to get first two characters in a string scratchmyhead 2 2,119 May-19-2020, 11:00 AM
Last Post: scratchmyhead
  Remove escape characters / Unicode characters from string DreamingInsanity 5 13,863 May-15-2020, 01:37 PM
Last Post: snippsat
  Replacing characters in a string with a list cjms981 1 1,836 Dec-30-2019, 10:50 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

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