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:])
Related
For my comp sci class I was assigned to make an english to pirate dictionary. The user is prompted to enter a sentence which is then translated to pirate but it isn't working and I'm not sure why. Any help would be appreciated.
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate: ")
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
print(b)
Your loop is iterating over range(len(a)), so x will take on an integer value for each individual character in your input. This is off for a couple of reasons:
Your goal is to iterate over words, not characters.
Indexing the dictionary should be done with words, not integers (this is the cause of your error).
Finally, note that .replace() replaces the first occurrence of the searched item in the string. To revise your approach to this problem in a way that still uses that method, consider these two main changes:
Iterate over the keys of the dictionary; the words that could potentially be replaced.
Loop until no such words exist in the input, since replace only does individual changes.
You're iterating over each of the characters in the string input, as the other answer before this has said, replace only replaces the first occurence.
You'd want to do something like this (after you've made your dictionary).
a = input("Please enter a sentence to be translated into pirate: ")
for x in eng2pir:
while x in a:
a = a.replace(x,eng2pir[x])
print(a)
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
because for loop x is int
but eng2pir dict no int key
so output error
#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate:\n ")
lst = a.split()
b = ''
for word in lst:
b += eng2pir.get(word, "")
print(b)
I'm writing a function where the user inputs a word, then inputs a string, and the function identifies all occurrences and the position of that word in a string (although it's actually converted to a list halfway through).
The code I have currently is only identifying the first occurrence of the word, and none further. It also doesn't identify the word if the word is the first word in the string, returning an empty list. It will also say the word's actual position - 1, as the first word is counted as zero.
I have attempted to curb this problem in two ways, the first of which doing a aString.insert(0, ' '), the second of which doing for i in __: if i == int: i += 1. Neither of these work.
Also, when doing the .insert, I tried putting a character in the space instead of, well, a space (as this part doesn't get printed anyway), but that didn't work.
Here is the code:
def wordlocator(word):
yourWord = word
print("You have chosen the following word: " +yourWord)
aString = input("What string would you like to search for the given word?")
aString = aString.lower()
aString = aString.split()
b = [(i, j) for i, j in enumerate(aString)]
c = [(i, x) for i, x in b if x == yourWord]
return c
The output I'm looking for is that if someone did...
wordlocator("word")
"please input a string generic message" "that is a word"
"4, word"
Currently that would work, but it'd print "3, word". If the string was "that is a word and this is also a word" then it'd ignore the further occurrence of "word".
edit: Got it working now, used a simpler piece of code. Thanks for your help all!
Try this:
def wordlocator(word):
yourWord = word
print("You have chosen the following word: " +yourWord)
aString = raw_input("What string would you like to search for the given word?")
aString = aString.lower()
aString = aString.split()
b = [(i+1, j) for i, j in enumerate(aString) if j == yourWord.lower()]
return b
print wordlocator('word')
note that the list comprehension can be filtered on just the match you are looking for. Actually I just changed it
I get this:
What string would you like to search for the given word?This word is not that word is it?
[(2, 'word'), (6, 'word')]
Note that the index is off by one if that matters, add one to x in the comprehension
A new test:
You have chosen the following word: word
What string would you like to search for the given word?word is the word
[(1, 'word'), (4, 'word')]
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.
I'm preparing for an exam but I'm having difficulties with one past-paper question. Given a string containing a sentence, I want to find the longest word in that sentence and return that word and its length. Edit: I only needed to return the length but I appreciate your answers for the original question! It helps me learn more. Thank you.
For example: string = "Hello I like cookies". My program should then return "Cookies" and the length 7.
Now the thing is that I am not allowed to use any function from the class String for a full score, and for a full score I can only go through the string once. I am not allowed to use string.split() (otherwise there wouldn't be any problem) and the solution shouldn't have too many for and while statements. The strings contains only letters and blanks and words are separated by one single blank.
Any suggestions? I'm lost i.e. I don't have any code.
Thanks.
EDIT: I'm sorry, I misread the exam question. You only have to return the length of the longest word it seems, not the length + the word.
EDIT2: Okay, with your help I think I'm onto something...
def longestword(x):
alist = []
length = 0
for letter in x:
if letter != " ":
length += 1
else:
alist.append(length)
length = 0
return alist
But it returns [5, 1, 4] for "Hello I like cookies" so it misses "cookies". Why? EDIT: Ok, I got it. It's because there's no more " " after the last letter in the sentence and therefore it doesn't append the length. I fixed it so now it returns [5, 1, 4, 7] and then I just take the maximum value.
I suppose using lists but not .split() is okay? It just said that functions from "String" weren't allowed or are lists part of strings?
You can try to use regular expressions:
import re
string = "Hello I like cookies"
word_pattern = "\w+"
regex = re.compile(word_pattern)
words_found = regex.findall(string)
if words_found:
longest_word = max(words_found, key=lambda word: len(word))
print(longest_word)
Finding a max in one pass is easy:
current_max = 0
for v in values:
if v>current_max:
current_max = v
But in your case, you need to find the words. Remember this quote (attribute to J. Zawinski):
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
Besides using regular expressions, you can simply check that the word has letters. A first approach is to go through the list and detect start or end of words:
current_word = ''
current_longest = ''
for c in mystring:
if c in string.ascii_letters:
current_word += c
else:
if len(current_word)>len(current_longest):
current_longest = current_word
current_word = ''
else:
if len(current_word)>len(current_longest):
current_longest = current_word
A final way is to split words in a generator and find the max of what it yields (here I used the max function):
def split_words(mystring):
current = []
for c in mystring:
if c in string.ascii_letters:
current.append(c)
else:
if current:
yield ''.join(current)
max(split_words(mystring), key=len)
Just search for groups of non-whitespace characters, then find the maximum by length:
longest = len(max(re.findall(r'\S+',string), key = len))
For python 3. If both the words in the sentence is of the same length, then it will return the word that appears first.
def findMaximum(word):
li=word.split()
li=list(li)
op=[]
for i in li:
op.append(len(i))
l=op.index(max(op))
print (li[l])
findMaximum(input("Enter your word:"))
It's quite simple:
def long_word(s):
n = max(s.split())
return(n)
IN [48]: long_word('a bb ccc dddd')
Out[48]: 'dddd'
found an error in a previous provided solution, he's the correction:
def longestWord(text):
current_word = ''
current_longest = ''
for c in text:
if c in string.ascii_letters:
current_word += c
else:
if len(current_word)>len(current_longest):
current_longest = current_word
current_word = ''
if len(current_word)>len(current_longest):
current_longest = current_word
return current_longest
I can see imagine some different alternatives. Regular expressions can probably do much of the splitting words you need to do. This could be a simple option if you understand regexes.
An alternative is to treat the string as a list, iterate over it keeping track of your index, and looking at each character to see if you're ending a word. Then you just need to keep the longest word (longest index difference) and you should find your answer.
Regular Expressions seems to be your best bet. First use re to split the sentence:
>>> import re
>>> string = "Hello I like cookies"
>>> string = re.findall(r'\S+',string)
\S+ looks for all the non-whitespace characters and puts them in a list:
>>> string
['Hello', 'I', 'like', 'cookies']
Now you can find the length of the list element containing the longest word and then use list comprehension to retrieve the element itself:
>>> maxlen = max(len(word) for word in string)
>>> maxlen
7
>>> [word for word in string if len(word) == maxlen]
['cookies']
This method uses only one for loop, doesn't use any methods in the String class, strictly accesses each character only once. You may have to modify it depending on what characters count as part of a word.
s = "Hello I like cookies"
word = ''
maxLen = 0
maxWord = ''
for c in s+' ':
if c == ' ':
if len(word) > maxLen:
maxWord = word
word = ''
else:
word += c
print "Longest word:", maxWord
print "Length:", len(maxWord)
Given you are not allowed to use string.split() I guess using a regexp to do the exact same thing should be ruled out as well.
I do not want to solve your exercise for you, but here are a few pointers:
Suppose you have a list of numbers and you want to return the highest value. How would you do that? What information do you need to track?
Now, given your string, how would you build a list of all word lengths? What do you need to keep track of?
Now, you only have to intertwine both logics so computed word lengths are compared as you go through the string.
My proposal ...
import re
def longer_word(sentence):
word_list = re.findall("\w+", sentence)
word_list.sort(cmp=lambda a,b: cmp(len(b),len(a)))
longer_word = word_list[0]
print "The longer word is '"+longer_word+"' with a size of", len(longer_word), "characters."
longer_word("Hello I like cookies")
import re
def longest_word(sen):
res = re.findall(r"\w+",sen)
n = max(res,key = lambda x : len(x))
return n
print(longest_word("Hey!! there, How is it going????"))
Output : there
Here I have used regex for the problem. Variable "res" finds all the words in the string and itself stores them in the list after splitting them.
It uses split() to store all the characters in a list and then regex does the work.
findall keyword is used to find all the desired instances in a string. Here \w+ is defined which tells the compiler to look for all the words without any spaces.
Variable "n" finds the longest word from the given string which is now free of any undesired characters.
Variable "n" uses lambda expressions to define the key len() here.
Variable "n" finds the longest word from "res" which has removed all the non-string charcters like %,&,! etc.
>>>#import regular expressions for the problem.**
>>>import re
>>>#initialize a sentence
>>>sen = "fun&!! time zone"
>>>res = re.findall(r"\w+",sen)
>>>#res variable finds all the words and then stores them in a list.
>>>res
Out: ['fun','time','zone']
>>>n = max(res)
Out: zone
>>>#Here we get "zone" instead of "time" because here the compiler
>>>#sees "zone" with the higher value than "time".
>>>#The max() function returns the item with the highest value, or the item with the highest value in an iterable.
>>>n = max(res,key = lambda x:len(x))
>>>n
Out: time
Here we get "time" because lambda expression discards "zone" as it sees the key is for len() in a max() function.
list1 = ['Happy', 'Independence', 'Day', 'Zeal']
listLen = []
for i in list1:
listLen.append(len(i))
print list1[listLen.index(max(listLen))]
Output - Independence
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