tags:

views:

57

answers:

3

My code as follow:

#!/usr/bin/python
#Filename:2_7.py
text=raw_input("Enter string:")
for ?? in range(??)
    print 

the ?? means I don't know how to write, could you please tell me if you know, thanks

+1  A: 

Do you want to split the string into separate words and print each one?

e.g.

for word in text.split():
    print word

in action:

Enter string: here are some words
here
are
some
words
mikej
+1  A: 

Maybe you want something like this?

var = raw_input("Enter something: ")
print "you entered ", var
Profeten
A: 

Well, for a simplistic case, you could try:

for word in text.split(" "):
    print word

For a more complex case where you want to use a regular expression for a splitter:

for word in re.split("\W+", text):
    if word != "":
        print word

The earlier example will output "Hello, my name is Pax." as:

Hello,
my
name
is
Pax.

while the latter will more correctly give you:

Hello
my
name
is
Pax

(and you can improve the regex if you have more edge cases).

paxdiablo
why do you need the square brackets? what's the difference between splitting on \W+ and [\W]+ ?. Why is it you have to check for "" ??
ghostdog74
I left the square brackets in from an earlier invocation since I was checking for multiple characters. You're right that they're not needed in this case. The reason I check for an empty string is specifically because of the ending period. By splitting that sample sentence on `\W+`, you get an empty element at the end, or beginning if you're working in one of those languages that has punctuation at the start. ¿yes?
paxdiablo