【问题标题】:How To Print Iterated String together(without new lines) in Python?如何在 Python 中一起打印迭代字符串(没有新行)?
【发布时间】:2014-09-17 16:37:21
【问题描述】:

我希望输出是 xyz 但它的到来就像
x
是的
z
当我在 for 循环中迭代我的字符串时,仍然有任何方法可以在迭代后一起打印字符串? 我的简单 Py 代码 =>

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

【问题讨论】:

  • print string 出了什么问题?

标签: python loops for-loop iteration


【解决方案1】:

你是说这个吗?

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

更新:根据您的评论,您可以做一些其他事情:

a) 使用 sys.stdout

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

b) 使用打印功能:

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

更多关于这个 SO 答案:How do I keep Python print from adding newlines or spaces?

【讨论】:

  • 是的! :P SomeThing like this 但是有空格我可以删除它们吗?
  • @user3881949 在 Python 3.x(或 2.x 使用 from __future__ import print_function)上,您可以使用 print(letter, end="")
【解决方案2】:

嗯,我真的很笨!!我刚刚修复了它:P Thnx 为大家提供帮助:)

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

【讨论】:

  • ...你试过了吗:print(string)?为什么你认为你必须重建字符串?此外,如果您有一个类似['Hello', 'World'] 的字符串列表,您可以使用join 将这些字符串连接在一起:', '.join(['Hello', 'World!']) -> 'Hello, World!'
  • :P 我知道我刚刚问过这个因为我想为循环中字符串中的每个字符添加一些东西,我在这里没有提到,它现在正在工作 Thnx
【解决方案3】:
>>> a
'xyz'
>>> for i in a: sys.stdout.write(i)
xyz

【讨论】:

    【解决方案4】:

    你可以使用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多