Concatenating in for loop - python

it's a loop to reverse a string entered by the user, it reads letters in reverse and put them into a sentence. the problem is that, for example user's input is hello, the comma(,) in the last line of the code makes the output to be o l l e h, but if there isnt a comma there, the output will have each letter in a line. and concatenate (+) doesnt work it gives an error. What do i do so that the output would be olleh instead of o l l e h?
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
for index in range (end,-1,-1):
print phrase[index],

how about:
string = ''
for i in range(end, -1, -1):
string += phrase[i]
print string
However, an easier, cleaner way without the for loop is:
print phrase[::-1] # this prints the string in reverse
And also there is:
#As dougal pointed out below this is a better join
print ''.join(reversed(phrase))
#but this works too...
print ''.join(phrase[i] for i in range(end, -1, -1)) # joins letters in phrase together from back to front

To concatenate something, you have to have a string to concatenate to. In this case, you need a variable that is defined outside of the for loop so you can access it from within the for loop multiple times, like this:
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
mystr = ""
for index in range (end,-1,-1):
mystr += phrase[index]
print mystr
Note that you can also simply reverse a string in Python doing this:
reversedstr = mystr[::-1]
This is technically string slicing, using the third operator to reverse through the string.
Another possibility would be
reversedstr = ''.join(reversed(mystr))
reversed returns a reversed iterator of the iterator you passed it, meaning that you have to transform it back into a string using ''.join

Related

How would I execute this? Python

I am pretty new to python and would like to know how to write a program that asks the user to enter a string that contains the letter "a". Then, on the first line, the program should print the part of the string up to and including the certain letter, and on the second line should be the rest of the string.
For example...
Enter a word: Buffalo
Buffa
lo
This is what I have so far :
text = raw_input("Type something: ")
left_text = text.partition("a")[0]
print left_text
So, I have figured out the first part of printing the string all the way up to the certain letter but then don't know how to print the remaining part of the string.
Any help would be appreciated
If what you want is the first occurrence of a certain character, you can use str.find for that. Then, just cur the string into two pieces based on that index!
In python 3:
split_char = 'a'
text = input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print(left, '\n', right)
I don't have a python2 on hand to make sure, but I assume this should work on python 2:
split_char = 'a'
text = raw_input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print left + '\n' + right)
Another option that is far more concise is to use
left_text, sep, right_text = text.partition("a")
print (left_text + sep, '\n', right_text)
and then as suggested in the comments, thanks #AChampion !
You should have some knowledge about slicing and concatenating string or list. You can learn them here Slicing and Concatenating
word = raw_input('Enter word:') # raw_input in python 2.x and input in python 3.x
split_word = raw_input('Split at: ')
splitting = word.partition(split_word)
'''Here lets assume,
word = 'buffalo'
split_word = 'a'
Then, splitting variable returns list, storing three value,
['buff', 'a', 'lo']
To get your desire output you need to do some slicing and concatenate some value .
'''
output = '{}\n{}'.join(splitting[0] + splitting[1], splitting[2])
print(output)
First find the indices of the character in the given string, then print the string accordingly using the indices.
Python 3
string=input("Enter string")
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
indices=find(string, "a")
for index in indices[::-1]:
print(string[:index+1])
print(string[indices[-1]+1:])

Cannot remove two vowels in a row

I have to enter a string, remove all spaces and print the string without vowels. I also have to print a string of all the removed vowels.
I have gotten very close to this goal, but for some reason when I try to remove all the vowels it will not remove two vowels in a row. Why is this? Please give answers for this specific block of code, as solutions have helped me solve the challenge but not my specific problem
# first define our function
def disemvowel(words):
# separate the sentence into separate letters in a list
no_v = list(words.lower().replace(" ", ""))
print no_v
# create an empty list for all vowels
v = []
# assign the number 0 to a
a = 0
for l in no_v:
# if a letter in the list is a vowel:
if l == "a" or l == "e" or l == "i" or l == "o" or l == "u":
# add it to the vowel list
v.append(l)
#print v
# delete it from the original list with a
del no_v[a]
print no_v
# increment a by 1, in order to keep a's position in the list moving
else:
a += 1
# print both lists with all spaces removed, joined together
print "".join(no_v)
print "".join(v)
disemvowel(raw_input(""))
Mistakes
So there are a lot of other, and perhaps better approaches to solve this problem. But as you mentioned I just discuss your failures or what you can do better.
1. Make a list of input word
There are a lot of thins you could do better
no_v = list(words.lower().replace(" ", ""))
You don't replaces all spaces cause of " " -> " " so just use this instead
no_v = list(words.lower().translate( None, string.whitespace))
2. Replace for loop with while loop
Because if you delete an element of the list the for l in no_v: will go to the next position. But because of the deletion you need the same position, to remove all the vowels in no_v and put them in v.
while a < len(no_v):
l = no_v[a]
3. Return the values
Cause it's a function don't print the values just return them. In this case replace the print no_v print v and just return and print them.
return (no_v,v) # returning both lists as tuple
4. Not a mistake but be prepared for python 3.x
Just try to use always print("Have a nice day") instead of print "Have a nice day"
Your Algorithm without the mistakes
Your algorithm now looks like this
import string
def disemvowel(words):
no_v = list(words.lower().translate( None, string.whitespace))
v = []
a = 0
while a < len(no_v):
l = no_v[a]
if l == "a" or l == "e" or l == "i" or l == "o" or l == "u":
v.append(l)
del no_v[a]
else:
a += 1
return ("".join(no_v),"".join(v))
print(disemvowel("Stackoverflow is cool !"))
Output
For the sentence Stackoverflow is cool !\n it outputs
('stckvrflwscl!', 'aoeoioo')
How I would do this in python
Not asked but I give you a solution I would probably use. Cause it has something to do with string replacement, or matching I would just use regex.
def myDisemvowel(words):
words = words.lower().translate( None, string.whitespace)
nv = re.sub("[aeiou]*","", words)
v = re.sub("[^a^e^i^o^u]*","", words)
return (nv, v)
print(myDisemvowel("Stackoverflow is cool !\n"))
I use just a regular expression and for the nv string I just replace all voewls with and empty string. For the vowel string I just replace the group of all non vowels with an empty string. If you write this compact, you could solve this with 2 lines of code (Just returning the replacement)
Output
For the sentence Stackoverflow is cool !\n it outputs
('stckvrflwscl!', 'aoeoioo')
You are modifying no_v while iterating through it. It'd be a lot simpler just to make two new lists, one with vowels and one without.
Another option is to convert it to a while loop:
while a < len(no_v):
l = no_v[a]
This way you have just a single variable tracking your place in no_v instead of the two you currently have.
For educational purposes, this all can be made significantly less cumbersome.
def devowel(input_str, vowels="aeiou"):
filtered_chars = [char for char in input_str
if char.lower() not in vowels and not char.isspace()]
return ''.join(filtered_chars)
assert devowel('big BOOM') == 'bgBM'
To help you learn, do the following:
Define a function that returns True if a particular character has to be removed.
Using that function, loop through the characters of the input string and only leave eligible characters.
In the above, avoid using indexes and len(), instead iterate over characters, as in for char in input_str:.
Learn about list comprehensions.
(Bonus points:) Read about the filter function.

Comparing two strings and returning the difference. Python 3 [duplicate]

This question already has answers here:
How to merge lists into a list of tuples?
(10 answers)
Closed 7 years ago.
My goal is to write a program which compares two strings and displays the difference between the first two non-matching characters.
example:
str1 = 'dog'
str2 = 'doc'
should return 'gc'
I know that the code which I have tried to use is bad but I am hoping to receive some tips. Here is my poor attempt to solve the exercise which leads me to nowhere:
# firstly I had tried to split the strings into separate letters
str1 = input("Enter first string:").split()
str2 = input("Enter second string:").split()
# then creating a new variable to store the result after comparing the strings
result = ''
# after that trying to compare the strings using a for loop
for letter in str1:
for letter in str2:
if letter(str1) != letter(str2):
result = result + letter
print (result)
def first_difference(str1, str2):
for a, b in zip(str1, str2):
if a != b:
return a+b
Usage:
>>> first_difference('dog','doc')
'gc'
But as #ZdaR pointed out in a comment, result is undefined (in this case None) if one string is a prefix of the other and has different length.
I changed the solution by using a single loop.
How about this:
# First, I removed the split... it is already an array
str1 = input("Enter first string:")
str2 = input("Enter second string:")
#then creating a new variable to store the result after
#comparing the strings. You note that I added result2 because
#if string 2 is longer than string 1 then you have extra characters
#in result 2, if string 1 is longer then the result you want to take
#a look at is result 2
result1 = ''
result2 = ''
#handle the case where one string is longer than the other
maxlen=len(str2) if len(str1)<len(str2) else len(str1)
#loop through the characters
for i in range(maxlen):
#use a slice rather than index in case one string longer than other
letter1=str1[i:i+1]
letter2=str2[i:i+1]
#create string with differences
if letter1 != letter2:
result1+=letter1
result2+=letter2
#print out result
print ("Letters different in string 1:",result1)
print ("Letters different in string 2:",result2)

python slicing substrings or strings

If I have a string 'banana peel' and I want to break it down to a width of 3 characters as in:
'ban'
'ana'
'pee'
'l'
How would I go about that? How would I remove the space/whitespace between 'banana' and 'peel' that is in the middle of the string and create the results above?
Only things that come to mind are things like list() and strip()
Just like this:
string = "banana peel"
string = string.replace(" ", "")
results = []
for i in range(0, len(string), 3):
results.append(string[i:i + 3])
print(results)
replace(" ", "") replaces all the spaces with nothing, giving bananapeel. range(0, len(string), 3) will give a list of numbers from 0 to the length of the string with an interval of 3. Each set gets added to the array for you to print in the end.

Advice on python program

So i had to write a program that asks for a user input (which should be a 3 letter string) and it outputs the six permutations of the variations of the placements of the letters inside the string. However, my professor wants the output to be surrounded by curly brackets whereas mine is a list (so it is square brackets). How do i fix this? Also, how do I check if none of the letters in the input repeat so that the main program keeps asking the user to enter input and check it for error?
Thank you
The only datatype im aware of that 'natively' outputs with { } is a dictionary, which doesnt seem to apply here. I would just write a small function to output your lists in the desired fashion
>>> def curlyBracketOutput(l):
x = ''
for i in l: x += i
return '{' + x + '}'
>>> curlyBracketOutput(['a','b','c'])
'{abc}'
ok, for one thing, as everyone here has said, print '{'. other than that, you can use the following code in your script to check for repeated words,
letterlist = []
def takeInput(string):
for x in string:
if x not in letterlist:
letterlist.append(x)
else:
return 0
return 1
then as for your asking for input and checking for errors, you can do that by,
while(True): #or any other condition
string = input("Enter 3 letter string")
if len(string)!=3:
print("String size inadequate")
continue
if takeInput(string):
arraylist = permutation(string) #--call permutation method here
#then iterate the permutations and print them in {}
for x in arraylist: print("{" + x + "}")
else:
print("At least one of the letters already used")
The answer to both question is to use a loop.
Print the "{" and then loop through all the elements printing them.
But the input inside a loop and keep looping until you get what you want.
Curly brackets refers to a dict?
I think a
list(set(the_input))
should give you a list of unique letters. to check if they occur more than once
and
theinput.count(one_letter) > 1
should tell you if there is mor than one.
>>> chars = ['a','b','c']
>>> def Output(chars):
... return "{%s}" % ''.join(chars)
...
>>> print Output(chars)
{abc}
>>>
Or just do something tremendously kludgy:
print repr(YourExistingOutput).replace("[", "{").replace("]", "}")

Categories