简体   繁体   中英

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.

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. 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. 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 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

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

You are casting space char to 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(' ') :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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