0

I Want the output to be xyz but its coming like
x
y
z
as I am iterating over my string in for loop but Still any Way to print string together after iterating? My Simple Py Code =>

string='xyz'
for lel in string:
                        print lel
1
  • What was wrong with print string? Commented Sep 17, 2014 at 16:41

4 Answers 4

2

You mean this?

string = "xyz"
for letter in string:
    print letter,

Update: According to your comment, you can do some other things:

a) Use sys.stdout

for letter in string:
    sys.stdout.write(letter)

b) Use the print function:

from __future__ import print_function
for letter in string:
    print(letter, end='')

More about in this SO answer: How do I keep Python print from adding newlines or spaces?

Sign up to request clarification or add additional context in comments.

2 Comments

yea!! :P SomeThing like this but there are spaces Can I Remove them even?
@user3881949 on Python 3.x (or 2.x using from __future__ import print_function) you can use print(letter, end="").
0

Well I Was really being Dumb!! I Just Fixed it up :P Thnx For The Help everyone :)

string='xyz'
x=''
for lel in string:
                  x+=lel
print x

2 Comments

... did you try: print(string)? Why do you think you have to rebuild the string? Also, if you have a list of strings like ['Hello', 'World'] you can use join to join the strings together: ', '.join(['Hello', 'World!']) -> 'Hello, World!'.
:P I Know i just asked this Coz i Want to add something to every Char in the string in the loop which i Didn't mention here , its Working now Thnx
0
>>> a
'xyz'
>>> for i in a: sys.stdout.write(i)
xyz

Comments

0

You could use:

import sys
text = "xyz"
for l in text:
    sys.stdout.write(l)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.