Print all words in a String without split() function - string

I want to print out all words in a string, line by line without using split() funcion in Python 3.
The phrase is a str(input) by the user, and it has to print all the words in the string, no matter it's size.Here's my code:
my_string = str(input("Phrase: "))
tam = len(my_string)
s = my_string
ch = " "
cont = 0
for i, letter in enumerate(s):
if letter == ch:
#print(i)
print(my_string[cont:i])
cont+=i+1
The output to this is:
Phrase: Hello there my friend
Hello
there
It is printing only two words in the string, and I need it to print all the words , line by line.

My apologies, if this isn't a homework question, but I will leave you to figure out the why.
a = "Hello there my friend"
b = "".join([[i, "\n"][i == " "] for i in a])
print(b)
Hello
there
my
friend
Some variants you can add to the process which you can't get easily with if-else syntax:
print(b.Title()) # b.lower() or b.upper()
Hello
There
My
Friend

def break_words(x):
x = x + " " #the extra space after x is nessesary for more than two word strings
strng = ""
for i in x: #iterate through the string
if i != " ": #if char is not a space
strng = strng+i #assign it to another string
else:
print(strng) #print that new string
strng = "" #reset new string
break_words("hell o world")
output:
hell
o
world

Related

how to remove special word from a string in function

Write a function fun(long string) with one string parameter that returns a string. The function should extract the words separated by a single space " ", exclude/drop empty words as well as words that are equal to "end" and "exit", convert the remaining words to upper case, join them with the joining token string ";" and return this newly joined string.
my code is......
def fun(long_string):
long_string = long_string.split(' ')
try:
if 'exit' in long_string:
long_string.remove('exit')
elif 'end' in long_string:
long_string.remove('end')
except ValueError:
pass
.....................
but it does not remove the "End or exit" .can someone pls help me to get it out. Im beginner in python and I stack here
You could try this and convert into the function as you wish - it's very straightforward.
Code did not fully test yet (but works for your inputs), so please try different inputs and you can learn to "improve" it to meet your requirement. Please ask if you have any questions.
inputs = "this is a long test exit string"
stop_words = ('end', 'exit')
outs = ''
for word in inputs.split():
if word in stop_words:
outs = inputs.replace(word, " ")
ans = ';'.join(w.upper() for w in outs.split()) # do the final conversion
Confirm it:
assert ans == "THIS;IS;A;LONG;TEST;STRING" # silent means True
Edit: add function:
def fun(long_string):
#s = "this is a long test exit string"
stop_words = ('end', 'exit')
outs = ''
for word in long_string.split():
if word in stop_words:
outs = long_string.replace(word, " ")
ans = ';'.join(w.upper() for w in outs.split())
return ans
text = "this is a long test exit string"
print(fun(text))

Concatenating string outputs of a for loop in Python 3

I have a code which, after a nested for loop, provides me with a unique string in each iteration. I want to find a way to concatenate those outputs so that my final line is a single string of those unique strings. Ignoring how ugly and inefficient this code is, what steps can I take to achieve the desired result?
VOWELS = ('a','e','i','o','u','A','E','I','O','U')
ad = "Desirable unfurnished flat in quiet residential area"
# remove all vowels, unless the word starts with a vowel
def is_vowel(c):
return c in VOWELS
def mod3(ad):
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
print(modAd)
mod3(ad)
my output for this code:
Otherwise, when I modify my code to look like this:
But my output is:
I don't believe a .join() would work here as it's not a list type. And I can't figure out where to put a string concat + anywhere without my for loop going bonkers. Any advice?
You can create a string result where you can concatenate your each iteration result and print that. You need to add spaces after each addition of words. So, append + " " to your result variable as well.
def mod3(ad):
result = ""
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
result += modAd + " "
print(result)
Second option: This is my take on it:
def mod4(ad):
result = ""
testAd =ad.split()
for word in testAd:
for i, char in enumerate(word):
if i == 0:
result += char
if i > 0 and char not in VOWELS:
result += char
result += " "
print(result)

How do I replace vowels for another value?(a to e, e to i, etc.)

I need to be able to have a user input a string, and my code is supposed to look at the string and change the vowels. So all the a's become e's, all the e's become i's, and so on. This is what I have, but I don't know how to make it work correctly.
def askForString():
userString=str(input("Enter a string: "))
userString=userString.lower()
return userString
def changeVowels(theString,vowels):
newString=[]
#newVowels=['e','i','o','u','a']
for i in range(len(theString)):
if theString[i] in vowels:
i+=newString
newString.append(i)
return newString
def main():
theString=askForString()
vowels=["a","e","i","o","u"]
NewString=changeVowels(theString,vowels)
print(NewString)
main()
I think I need to somehow have the vowels change into new vowels, but I cannot figure out how. That's why I have it as a comment.
The line i+=newString is erraneous.
i is an integer while newString is a list. You cannot add an integer to a list.
From the question I gather that you need to replace the vowels in your string as follows:
a -> e
e -> i
i -> o
o -> u
u -> a
You have multiple ways to achieve that:
Method 1:
inputString = input() # input returns string by default, no need to call with with str()
outputString = ""
vowels = ['a','e','i','o','u']
for character in inputString:
if character in vowels:
vowelIndex = vowels.index(character) # get the index of the vowel
if vowelIndex == len(vowels)-1: # if its 'u', then we need to cycle back to 'a'
vowelIndex = 0
else:
vowelIndex += 1 # if its not 'u', then just add 1 to go to next index which gives us the next vowel
outputString += vowels[vowelIndex] # put that character into the outputString
else:
outputString += character # if not vowel, then just put that character into the string.
print(outputString)
Method 2: Using dictionary to directly map the vowel to next vowel
vowels = {
"a" : "e",
"e" : "i",
"i" : "o",
"o" : "u",
"u" : "a"
}
inputString = input()
outputString = ""
for character in inputString:
if character in vowels: # checks the a key named "character" exists in the dictionary "vowels
outputString += vowels[character]
else:
outputString += character
print(outputString)
def changeVowels(theString, vowels):
newString=[]
repls = dict(zip(vowels, vowels[1:]+[vowels[0]]))
for theLetter in theString:
if theLetter in vowels:
theLetter = repls[theLetter]
newString.append(theLetter)
return newString

Where is issue with final display in this code?

The code requires the user to provide an input of strings and convert the uppercase to lower and vice-versa.Input: Rohit Tapadia , Expected Output: rOHIT tAPADIA , Actual Output: rOHIt TAPADIA . It should do exactly what the swapcase() does.
inp = input("Enter ")
for i in inp:
inp_lst.append(i)
print(inp_lst)
for j in inp_lst:
if j.isupper()==True:
x=inp_lst.index(j)
#print(x)
#print(j)
k = j.lower()
#print(k)
inp_lst[x]=k
print(inp_lst[x])
elif j.islower()==True:
y=inp_lst.index(j)
#print(y)
#print(j)
l = j.upper()
inp_lst[y]=l
print(inp_lst[y])
else:
z=inp_lst.index(j)
#print(z)
#print(j)
inp_lst[z]=j
print(inp_lst[z])
print(''.join(inp_lst))```
You can achieve exactly the same thing in 2 lines with the built-in swapcase() method:
inp = input("Enter ")
print(inp.swapcase())
Example input:
heLLo StackOverflow
Output:
HEllO sTACKoVERFLOW
Demo: https://repl.it/#glhr/55548482
Edit: here's a working and simplified implementation of your code. Note that inp_lst is not needed since you can directly iterate over characters in a string. You can simply add each character to the output string using string concatenation (not that outputString += j is equivalent to outputString = outputString + j - it simply adds j at the end of the string).
inp = input("Enter ")
outputString = ""
for j in inp:
if j.isupper():
outputString += j.lower()
elif j.islower():
outputString += j.upper()
else:
outputString += j
print(outputString)
Edit 2: The problem in your code is this inp_lst.index(j), because index() searches for the first occurrence of the character j. So if j='t', it will select the first occurrence of t in the list, and turn it uppercase/lowercase, even if the loop is at the second occurrence of t. That's why the first t in "Rohit Tapadia" is turned to lowercase in the output.
you can try this one too
inp = input("Enter ")
output="".join([char.lower() if char.isupper() else char.upper() for char in inp ])
inp = "Rohit Tapadia"
output will be
rOHIT tAPADIA

How would I reverse each word individually rather than the whole string as a whole

I'm trying to reverse the words in a string individually so the words are still in order however just reversed such as "hi my name is" with output "ih ym eman si" however the whole string gets flipped
r = 0
def readReverse(): #creates the function
start = default_timer() #initiates a timer
r = len(n.split()) #n is the users input
if len(n) == 0:
return n
else:
return n[0] + readReverse(n[::-1])
duration = default_timer() - start
print(str(r) + " with a runtime of " + str(duration))
print(readReverse(n))
First split the string into words, punctuation and whitespace with a regular expression similar to this. Then you can use a generator expression to reverse each word individually and finally join them together with str.join.
import re
text = "Hello, I'm a string!"
split_text = re.findall(r"[\w']+|[^\w]", text)
reversed_text = ''.join(word[::-1] for word in split_text)
print(reversed_text)
Output:
olleH, m'I a gnirts!
If you want to ignore the punctuation you can omit the regular expression and just split the string:
text = "Hello, I'm a string!"
reversed_text = ' '.join(word[::-1] for word in text.split())
However, the commas, exclamation marks, etc. will then be a part of the words.
,olleH m'I a !gnirts
Here's the recursive version:
def read_reverse(text):
idx = text.find(' ') # Find index of next space character.
if idx == -1: # No more spaces left.
return text[::-1]
else: # Split off the first word and reverse it and recurse.
return text[:idx][::-1] + ' ' + read_reverse(text[idx+1:])

Resources