I am trying get user input and seperate it letter by letter and also replace " " with "SPACE" This is what i have so far
word= input("Enter a word")
for index, letter in enumerate(word,1):
print("str[",index,"]:",letter)
For this It Gives an Output Like
str[ 1 ]: H
str[ 2 ]: e
str[ 3 ]: l
str[ 4 ]: l
str[ 5 ]: o
str[ 6 ]:
str[ 7 ]: W
str[ 8 ]: o
str[ 9 ]: r
str[ 10 ]: l
str[ 11 ]: d
How can i turn it into something like
str[ 1 ]: H
str[ 2 ]: e
str[ 3 ]: l
str[ 4 ]: l
str[ 5 ]: o
str[ 6 ]: SPACE
str[ 7 ]: W
str[ 8 ]: o
str[ 9 ]: r
str[ 10 ]: l
str[ 11 ]: d
CodePudding user response:
This is fairly easy. You can try matching the letter with a string containing space:
word= input("Enter a word ")
for index, letter in enumerate(word,1):
if letter == " ":
print("str[",index,"]:","SPACE")
else:
print("str[",index,"]:",letter)
CodePudding user response:
for index, letter in enumerate(word,1):
print('str[', index, ']:', letter.replace(' ', 'SPACE'))
CodePudding user response:
You could use str.strip
and if that results in an empty string, use 'SPACE'
for index, letter in enumerate(word,1):
print(f"str[ {index} ]: {letter.strip() or 'SPACE'}")
CodePudding user response:
Look at this code:
def replaceall(word,string,replacement):
word = list(word) #List the word for easy enumeration and print
indices = [i for i,x in enumerate(word) if x == string] #Get all the index of the strings in the list
for i in indices:
word[i] = replacement #Assign replacement to string's position in the list
return word #Return listed word because if you use enumerate in word it will print the letters of 'space' out
replaceall('hello world')
>>> ['h', 'e', 'l', 'l', 'o', 'SPACE', 'w', 'o', 'r', 'l', 'd']
After that use enumerate and for loop to do what you want.