I'm trying to put together a code that will basically take a user input string and reprint every 3rd character.

i.e.

if a user inputs "Superman" it should be reprinted like "S e a"

I'm sure this is Uber-simple to you but I'm just starting out, whether it is efficient at this point doesn't matter.

I do know the command to count how many of what letter there are like this:

>>> cnt = {}
>>> for c in s:
	cnt[c] = cnt.get(c,0) + 1

But obviously that doesn't do what I want... Is there a simple way to do this?

Recommended Answers

All 3 Replies

What you want is in three pieces:

  1. The built in function range() which takes three parameters: first, last+1 and step. Use this to create a sequence of indices into your string. I'm not going to do this for you: It is very simple.
  2. List comprehension (see note below) that builds a list from a sequence: Build the list of your letters using the indices from the range. Something like this: [my_string[x] for x in range(....)]
  3. The string method join() that concatenates elements of a list. Once again, this is very simple.

Using these three pieces, you can do what you need on one line. Even without the list comprehension, you can do it in a simple loop, where you use the += operator to append the next character to the subsequence string you are buliding.

Note: You don't really need to use list comprehension, since str.join works with any sequence, including a generated one. The generator form of a comprehension is slightly more efficient than the list form... if the list would get large, anyhow. In your case it probably doesn't matter at all. If you don't understand what I just said, you might want to go back and read the list comprehension doc again. Or wait until you get to generators in your studies.

By the way: Thanks for finding and using the (CODE) button. Be sure to use the 'this thread is solved' link when, in fact, the thread is solved.

thanks a lot for those links and brief explanation! It really does help, I appreciate it

And now at the end, the thing griswolf left out. It is example of power of Python that the thing you wanted requires not one line but 5 characters

[::3]
>>> raw_input()[::3]
Superman
'Sea'

Actually this is not so relevant, I write it just for later, when you maybe need to do it efficiently.

You have found some simple exercise which is helpfull for learning Python, and it does not matter that there is direct way to do it.

Luck for your adventure to Python world!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.