Reputation: 123
s = 'fo12--'
for a in s:
a+= 1
print(s[a])
I would expect
f o 1 2 - -
but getting some type error. I can guess 'a' is a int here, but how can I improve this code
Upvotes: 2
Views: 115
Reputation: 1970
Python 2/3:
Without variable:
print(' '.join("fo12--"))
With a variable:
a = "fo12--"
print(' '.join(a))
The join
method iterates through object and join them with a given string.
Upvotes: 1
Reputation: 43169
It is (for Python 3
):
s = 'fo12--'
for a in s:
print(a, end = " ")
For Python 2
:
s = 'fo12--'
for a in s:
print a,
See a demo on ideone.com.
a[index]
syntax known from other programming languages. If you want to have the index as well, enumerate()
is your friend:
s = 'fo12--'
for idx, char in enumerate(s):
# char holds the actual character
# idx is an increasing integer, starting from zero
Upvotes: 2
Reputation: 49803
You are using a
both for the individual characters of s
(your for a in s
) AND as an index into that string. Either will work, but you can't use it for both at the same time.
Upvotes: 0
Reputation: 2981
To do what your title says would just be:
s = 'fo12--'
for i in s:
print(i, end=' ')
But there are some fundamental problems with the code and the understanding of how it should perform (you saying that you guess 'a' is an int
).
I would certainly suggest going through a Python basics program or tutorial first, it will help you get to grips with the basics and understand what is happening under the hood, so to speak.
Good luck and enjoy! :)
Upvotes: 1