Reputation: 79
I'm kind of new to Python so if this is a silly mistake, please forgive me!
I have been working on a Password Generator to present at tech club. How it works is that it asks for you to type in a word. The word you enter is turned into a list. Then it changes each letter in the list to something else to make a unique password (it's flawed, I know). When I run the code, it says TypeError: string indices must be integers
. What is wrong with my code?
print ("Leo's Password Generator")
print ('Please enter a word')
word = input()
print ('Enter another word:')
word2 = input()
word = word2 + word
word.split()
def print_list(toon):
for i in toon:
if toon[i] == 'e':
toon[i] = '0'
print_list(word)
print (word)
Upvotes: 3
Views: 6384
Reputation: 5059
The problem is that you're passing a string to print_list
. When you iterate through a string, it splits it into single-character strings. So, essentially what you're doing is calling toon['a']
, which doesn't work, because you have to use an integer to access an iterable by index.
Note also that both you and Batuhan are making a mistake in the way you're dealing with strings. Even once you fix the error above, you're still going to get another one immediately afterwards. In python, string
doesn't allow item assignment, so you're going to have to create an entirely new string rather than reassigning a single character therein.
If you wanted, you could probably use a list comprehension to accomplish the same task in significantly less space. Here's an example:
def print_list(toon):
return ''.join([ch if ch != 'e' else '0' for ch in toon])
This creates a new string from toon where all incidences of 'e' have been replaced with '0', and all non-'e' characters are left as before.
Edit: I might have misunderstood your purpose. word.split()
as the entirety of a statement doesn't do anything - split
doesn't reassign, and you'd have to do word = word.split()
if you wanted to word to equal a list of strings after that statement. But - is there a reason you're trying to split the string in the first place? And why are you assigning two separate words to a single variable called word
? That doesn't make any sense, and makes it very difficult for us to tell what you're trying to accomplish.
Upvotes: 1
Reputation: 798
For loop
already gives you the value of the next available item. In your case, i
is not an index, it is the value itself.
However, if you want to reach to both index and the value, you can use enumerate
:
def print_list(toon):
for i, ch in enumerate(toon):
if ch == 'e':
toon = toon[:i] + '0' + toon[i+1:]
print(toon)
or you can iterate over the string in a traditional method:
def print_list(toon):
for i in range(len(toon)):
if toon[i] == 'e':
toon = toon[:i] + '0' + toon[i+1:]
print(toon)
EDIT:
As @furkle pointed out, since strings
are immutable
, they cannot be changed using indexes. So use concatenation, or replace
method.
Upvotes: 0