Python 使用 while 循环从字符串中一次打印一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15221516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:33:06  来源:igfitidea点击:

Printing one character at a time from a string, using the while loop

pythonwhile-loop

提问by Kevinvhengst

Im reading "Core Python Programming 2nd Edition", They ask me to print a string, one character at a time using a "while" loop.

我正在阅读“Core Python Programming 2nd Edition”,他们要求我使用“while”循环打印一个字符串,一次一个字符。

I know how the while loop works, but for some reason i can not come up with an idea how to do this. I've been looking around, and only see examples using for loops.

我知道 while 循环是如何工作的,但由于某种原因,我无法想出如何做到这一点。我一直在环顾四周,只看到使用 for 循环的示例。

So what i have to do:

所以我必须做的:

user gives input:

用户提供输入:

text = raw_input("Give some input:  ")

I know how to read out each piece of data from an array, but i can't remember anything how to do it to a string.

我知道如何从数组中读出每条数据,但我不记得如何对字符串执行任何操作。

Now all i need is working while-loop, that prints every character of the string, one at a time.

现在我所需要的只是工作 while 循环,它打印字符串的每个字符,一次一个。

i guess i've to use len(text), but i'm not 100% sure how to use it in this problem.

我想我必须使用 len(text),但我不是 100% 确定如何在这个问题中使用它。

Some help would be awsome! I'm sure this is a very simple issue, but for some reason i cannot come up with it!

一些帮助会很棒!我确定这是一个非常简单的问题,但由于某种原因我无法想出它!

Thx in advance! :)

提前谢谢!:)

采纳答案by Gjordis

I'm quite sure, that the internet is full of python while-loops, but one example:

我很确定,互联网上到处都是 python 的 while 循环,但举个例子:

i=0

while i < len(text):
    print text[i]
    i += 1

回答by akaIDIOT

Python allows you to use a string as an iterator:

Python 允许您使用字符串作为迭代器:

for character in 'string':
    print(character)

I'm guessing it's your job to figure out how to turn that into a while loop.

我猜你的工作是弄清楚如何把它变成一个 while 循环。

回答by acattle

Other answers have already given you the code you need to iterate though a string using a whileloop (or a forloop) but I thought it might be useful to explain the difference between the two types of loops.

其他答案已经为您提供了使用while循环(或for循环)遍历字符串所需的代码,但我认为解释这两种类型的循环之间的区别可能很有用。

whileloops repeat some code until a certain condition is met. For example:

while循环重复一些代码,直到满足某个条件。例如:

import random

sum = 0
while sum < 100:
    sum += random.randint(0,100) #add a random number between 0 and 100 to the sum
    print sum

This code will keep adding random numbers between 0 and 100 until the total is greater or equal to 100. The important point is that this loop could run exactly once (if the first random number is 100) or it could run forever (if it keeps selecting 0 as the random number). We can't predict how many times the loop will run until after it completes.

这段代码将不断添加 0 到 100 之间的随机数,直到总数大于或等于 100。重要的一点是,这个循环可以只运行一次(如果第一个随机数是 100),也可以永远运行(如果它保持选择 0 作为随机数)。我们无法预测循环将运行多少次,直到它完成。

forloops are basically just while loops but we use them when we want a loop to run a preset number of times. Java forloops usually use some sort of a counter variable (below I use i), and generally makes the similarity between whileand forloops much more explicit.

for循环基本上就是 while 循环,但是当我们希望循环运行预设次数时,我们会使用它们。Javafor循环通常使用某种计数器变量(下面我使用i),并且通常使whilefor循环之间的相似性更加明确。

for (int i=0; i < 10; i++) { //starting from 0, until i is 10, adding 1 each iteration
    System.out.println(i);
}

This loop will run exactly 10 times. This is just a nicer way to write this:

这个循环将精确运行 10 次。这只是一个更好的写法:

int i = 0;
while (i < 10) { //until i is 10
   System.out.println(i);
   i++; //add one to i 
}

The most common usage for a for loop is to iterate though a list (or a string), which Python makes very easy:

for 循环最常见的用法是遍历列表(或字符串),Python 使之变得非常简单:

for item in myList:
    print item

or

或者

for character in myString:
    print character

However, you didn't want to use a forloop. In that case, you'll need to look at each character using its index. Like this:

但是,您不想使用for循环。在这种情况下,您需要使用其索引查看每个字符。像这样:

print myString[0] #print the first character
print myString[len(myString) - 1] # print the last character.

Knowing that you can make a forloop using only a whileloop and a counter and knowing that you can access individual characters by index, it should now be easy to access each character one at a time using a whileloop.

知道您可以for仅使用while循环和计数器进行循环并知道您可以通过索引访问单个字符,现在使用while循环一次访问每个字符应该很容易。

HOWEVERin general you'd use a forloop in this situation because it's easier to read.

但是,通常for在这种情况下您会使用循环,因为它更易于阅读。

回答by andsoa

   # make a list out of text - ['h','e','l','l','o']
   text = list('hello') 

   while text:
       print text.pop()

:)

:)

In python empty object are evaluated as false. The .pop() removes and returns the last item on a list. And that's why it prints on reverse !

在 python 中,空对象被评估为 false。.pop() 删除并返回列表中的最后一项。这就是为什么它打印在反面!

But can be fixed by using:

但可以通过使用修复:

text.pop( 0 )

回答by JediPythonClone

Try this procedure:

试试这个程序:

def procedure(input):
    a=0
    print input[a]
    ecs = input[a] #ecs stands for each character separately
    while ecs != input:
        a = a + 1
        print input[a]

In order to use it you have to know how to use procedures and although it works, it has an error in the end so you have to work that out too.

为了使用它,您必须知道如何使用程序,尽管它有效,但最终会出错,因此您也必须解决它。

回答by LUCAS

This will print each character in text

这将打印文本中的每个字符

text = raw_input("Give some input:  ")
for i in range(0,len(text)):
   print(text[i])

回答by Private Caller

Strings can have for loops to:

字符串可以有 for 循环来:

for a in string:
    print a

回答by Don Bar

Python Code:

蟒蛇代码:

for s in myStr:
        print s

OR

或者

for i in xrange(len(myStr)):
    print myStr[i]

回答by Adiraamruta

Try this instead ...

试试这个...

Printing each character using while loop

使用 while 循环打印每个字符

i=0
x="abc"
while i<len(x) :
    print(x[i],end=" ")
    print(i)
    i+=1