1
import java.util.Scanner;

public class Testing {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a message");

        String message = input.nextLine();

        message = message.toLowerCase();
        message = message.replaceAll("\\s+", "");

        for(int i = 0; i < message.length(); i++) {
            //i = the position
            System.out.println(i);
            //z = the character at position i
            char z = message.charAt(i);
            System.out.println(z);
            }
         }
}

This java takes a string and returns each character along with its respective index from the message. I want to make some python that does the same thing.

message = raw_input( "Enter a message ")

message = message.replace(" ", "")
message = message.lower()

print message

for i in message :
    #i = each character in message
    print i
    #I want to print the position of character
    #i in the message
    print #????

I could use message.index(i) but when there are repeat letters it will only find the first.

How to find all occurrences of an element in a list?

This question was answered using indices, but that returns the values of all occurrences of that character. I only want one index at a time.

For example, if I input the message 'hello world' I want the output to be 0 h 1 e 2 l 3 l 4 0 etc. It was easy to do this with java because the for-loop creates the index first, then uses that index to find the character. The python code works a bit backwards, at least right now. First it finds every character in the message, but then I'm searching for that character in the message. Can I use a for-loop more similarly to the way I did in Java? is there a better way?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Henry Hale
  • 11
  • 1
  • I wasn't sure exactly which question was the closest duplicate for you; search around the site with `[python] enumerate` until you understand how it works. BTW, the `.replaceAll` in your Java takes out more than just spaces; a Python equivalent is `message = ''.join(message.split())`. – Karl Knechtel Oct 16 '19 at 05:14
  • @KarlKnechtel Thanks! I'll check it out. – Henry Hale Oct 16 '19 at 13:52

0 Answers0