简体   繁体   English

在for循环中将String转换为Int

[英]Typecasting a String into an Int within a for loop

How would I store the position variable i as an int so that I can play with that particular position within a string This will be displayed in a monospaced font. 如何将位置变量i存储为int,以便我可以在字符串中使用该特定位置。这将以等宽字体显示。

sentence = input()
for i in sentence:
    if i == " ":
        j = int(i) #this line is throwing an error 
        print (sentence[0:j])

There are two flaws within your code: 您的代码中存在两个缺陷:

if i == " ":
    j = int(i)

So you check whether i is a space character, in which case you want to convert that space into a number. 因此,检查i是否是空格字符,在这种情况下,您要将该空格转换为数字。 Of course that's not going to work—what number is that space supposed to mean? 当然那不会起作用 - 那个空间应该是什么意思?

The other flaw is the reason why you have a space character there. 另一个缺陷是你在那里有空间角色的原因。 You say that you want to use the position, or index, of the character. 你说你想要使用角色的位置或索引。 But your for loop does something different than what you expect: for x in sequence will iterate over every element x within that sequence. 但是你的for循环做了一些不同于你期望的事情: for x in sequence将迭代该序列中的每个元素x In case of a string sequence, you will get every character—not an index though. 在字符串序列的情况下,您将获得每个字符 - 而不是索引。

For example: 例如:

>>> for x in 'foo':
        print(x)

f
o
o

As you can see, it prints the characters, not the indexes. 如您所见,它打印的是字符,而不是索引。

You can use enumerate() for this though. 你可以使用enumerate() Enumerate will enumerate over a sequence giving you the value and the index it appeared at: 枚举将枚举一个序列,为您提供它出现的值索引:

>>> for i, x in enumerate('foo'):
        print(i, x)

0 f
1 o
2 o

So you get the index too. 所以你也得到了索引。

In your case, your code would look like this then: 在您的情况下,您的代码将如下所示:

sentence = input()
for i, x in enumerate(sentence):
    if x == " ":
        print(sentence[0:i])

You should use enumerate 你应该使用enumerate

for k, v in enumerate(sentence):
   if v == " ":
     print (sentence[0:k])

You are casting space char to int. 您正在将空格char转换为int。 Of course does not work. 当然不行。

>>> int(' ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

If You try to find position of ' ' use sentence.index(' ') : 如果你试图找到' ' use sentence.index(' ')

sentence = input()
try:
    i = sentence.index(' ')
    print (sentence[0:j])
except ValueError:
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM