Looping and Lists - Grok Learning - python

I've just started learning to code Python today on Grok Learning and I'm currently stuck on this problem. I have to create a code that reads a message and:
read the words in reverse order
only take the words in the message that start with an uppercase letter
make everything lowercase
I've done everything right but I can't get rid of a space at the end. I was wondering if anyone knew how to remove it. Here is my code:
code = []
translation = []
msg = input("code: ")
code = msg.split()
code.reverse()
for c in code:
if c[0].isupper():
translation.append(c)
print("says: ", end='')
for c in translation:
c = c.lower()
print(c, end = ' ')
Thank you :)

You need to iterate for all of the letters in translation but the last and print it separately without the space:
for c in translation[:-1]:
c = c.lower()
print(c, end = ' ')
print(translation[-1], end='')

You can simply use join() and f-strings.
result = ' '.join(translation).lower()
print(f"says: {result}")

This is a common problem:
You have a sequence of n elements
You want to format them in a string using a separator between the elements, resulting in n-1 separators
I'd say the pythonic way to do this, if you really want to build the resulting string, is str.join(). It takes any iterable, for example a list, of strings, and joins all the elements together using the string it was called on as a separator. Take this example:
my_list = ["1", "2", "3"]
joined = ", ".join(my_list)
# joined == "1, 2, 3"
In your case, you could do
msg = "Hello hello test Test asd adsa Das"
code = msg.split()
code.reverse()
translation = [c.lower() for c in code if c[0].isupper()]
print("says: ", end='')
print(" ".join(translation))
# output:
# says: das test hello
For printing, note that print can also take multiple elements and print them using a separator. So, you could use this:
print(*translation, sep=" ")
You could also leave out explicitly setting sep because a space is the default:
print(*translation)

Related

Printing every other letters of a string without the spaces on Python

I am trying to build a function that will take a string and print every other letter of the string, but it has to be without the spaces.
For example:
def PrintString(string1):
for i in range(0, len(string1)):
if i%2==0:
print(string1[i], sep="")
PrintString('My Name is Sumit')
It shows the output:
M
a
e
i
u
i
But I don't want the spaces. Any help would be appreciated.
Use stepsize string1[::2] to iterate over every 2nd character from string and ignore if it is " "
def PrintString(string1):
print("".join([i for i in string1[::2] if i!=" "]))
PrintString('My Name is Sumit')
Remove all the spaces before you do the loop.
And there's no need to test i%2 in the loop. Use a slice that returns every other character.
def PrintString(string1):
string1 = string1.replace(' ', '')
print(string1[::2])
Replace all the spaces and get every other letter
def PrintString(string1):
return print(string1.replace(" ", "") [::2])
PrintString('My Name is Sumit')
It depends if you want to first remove the spaces and then pick every second letter or take every second letter and print it, unless it is a space:
s = "My name is Summit"
print(s.replace(" ", "")[::2])
print(''.join([ch for ch in s[::2] if ch != " "]))
Prints:
MnmiSmi
Maeiumt
You could alway create a quick function for it where you just simply replace the spaces with an empty string instead.
Example
def remove(string):
return string.replace(" ", "")
There's a lot of different approaches to this problem. This thread explains it pretty well in my opinion: https://www.geeksforgeeks.org/python-remove-spaces-from-a-string/

Remove only trailing whitespace from output

I have a task that was assigned to me for homework. Basically the problem is:
Write a program that can get rid of the brand names and replace them with the generic names.
The table below shows some brand names that have generic names. The mapping has also been provided to you in your program as the BRANDS dictionary.
BRANDS = {
'Velcro': 'hook and loop fastener',
'Kleenex': 'tissues',
'Hoover': 'vacuum',
'Bandaid': 'sticking plaster',
'Thermos': 'vacuum flask',
'Dumpster': 'garbage bin',
'Rollerblade': 'inline skate',
'Asprin': 'acetylsalicylic acid'
}
This is my code:
sentence = input('Sentence: ')
sentencelist = sentence.split()
for c in sentencelist:
if c in BRANDS:
d = c.replace(c, BRANDS[c])
print(d, end=' ')
else:
print(c, end=' ')
My output:
Sentence: I bought some Velcro shoes.
I bought some hook and loop fastener shoes.
Expected output:
Sentence: I bought some Velcro shoes.
I bought some hook and loop fastener shoes.
It looks the same, but in my output there was an extra whitespace after 'shoes.' when there isn't supposed to be a whitespace. So how do I remove this whitespace?
I know you could do rstrip() or replace() and I tried it, but it would just jumble everything together when I just need to remove the trailing whitespace and not remove any other whitespace. If the user put the brand name in the middle of the sentence, and I used rstrip(), it would join the brand name and the rest of the sentence together.
The key is to use a string's join method to concatenate everything for you. For example, to put a space between a bunch of strings without putting a space after the last bit, do
' '.join(bunch_of_strings)
The strings have to be in an iterable, like a list, for that to work. You could make the list like this:
edited_list = []
for word in sentence_list:
if word in BRANDS:
edited_list.append(BRANDS[word])
else:
edited_list.append(word)
A much shorter alternative would be
edited_list = [BRANDS.get(word, word) for word in sentence_list]
Either way, you can combine the edited sentence using the join method:
print(' '.join(edited_list))
This being Python, you can do the whole thing as a one-liner without using an intermediate list at all:
print(' '.join(BRANDS.get(word, word) for word in sentence_list))
Finally, you could do the joining in print itself using splat notation. Here, you would pass in each element of your list as a separate argument, and use the default sep argument to insert the spaces:
print(*edited_list)
As an aside, d = c.replace(c, BRANDS[c]) is a completely pointless equivalent of just d = BRANDS[c]. Since strings are immutable, any time you do c.replace(c, ..., you are just returning the replacent in a somewhat illegible manner.
The problem is that print(c, end=' ') will always print a space after c. Here is a pretty minimal change to fix that:
sentence = input('Sentence: ')
sentencelist = sentence.split()
is_first = True
for c in sentencelist:
if not is_first:
print(' ', end='')
is_first = False
if c in BRANDS:
d = c.replace(c, BRANDS[c])
print(d, end='')
else:
print(c, end='')
As others have pointed out, this can be tidied up, e.g., d = c.replace(c, BRANDS[c]) is equivalent to d = BRANDS[c], and if you change it to c = BRANDS[c], then you could use a single print call and no else clause.
But you also have to be careful with your approach, because it will fail for sentences like "I bought a Hoover." The sentence.split() operation will keep "Hoover." as a single item, and that will fail the c in BRANDS test due to the extra period. You could try to separate words from punctuation, but that won't be easy. Another solution would be to apply all the replacements to each element, or equivalently, to the whole sentence. That should work fine in this case since you may not have to worry about replacement words that could be embedded in longer words (e.g., accidentally replacing 'cat' embedded in 'caterpillar'). So something like this may work OK:
new_sentence = sentence
for brand, generic in BRANDS.items():
new_sentence = new_sentence.replace(brand, generic)
print(new_sentence)
Your end=' ' unconditionally appends extra spaces to your output. There is no consistent way to undo this (echoing a backspace character only works for terminals, seeking only works for files, etc.).
The trick is to avoid printing it in the first place:
sentence = input('Sentence: ')
sentencelist = sentence.split()
result = []
for c in sentencelist:
# Perform replacement if needed
if c in BRANDS:
c = BRANDS[c] # c.replace(c, BRANDS[c]) is weird way to spell BRANDS[c]
# Append possibly replaced value to list of results
result.append(c)
# Add spaces only in between elements, not at the end, then print all at once
print(' '.join(result))
# Or as a trick to let print add the spaces and convert non-strings to strings:
print(*result)
You dont have to split the word and iterating through it.
Try this code it will work and will not get the issue of white space anymore
sentence = ' '.join(str(BRANDS.get(word, word)) for word in input_words)
Here,make a list names "input_words" and add the number of line that you wanted to process
Happy Learning!

split strings with multiple special characters into lists without importing anything in python

i need to make a program that will capitalize the first word in a sentence and i want to be sure that all the special characters that are used to end a sentence can be used.
i can not import anything! this is for a class and i just want some examples to do this.
i have tried to use if to look in the list to see if it finds the matching character and do the correct split operatrion...
this is the function i have now... i know its not good at all as it just returns the original string...
def getSplit(userString):
userStringList = []
if "? " in userString:
userStringList=userString.split("? ")
elif "! " in userStringList:
userStringList = userString.split("! ")
elif ". " in userStringList:
userStringList = userString.split(". ")
else:
userStringList = userString
return userStringList
i want to be able to input something like this is a test. this is a test? this is definitely a test!
and get [this is a test.', 'this is a test?', 'this is definitely a test!']
and the this is going to send the list of sentences to another function to make the the first letter capitalized for each sentence.
this is an old homework assignment that i could only make it use one special character to separate the string into a list. buti want to user to be able to put in more then just one kind of sentence...
This may hep. use str.replace to replace special chars with space and the use str.split
Ex:
def getSplit(userString):
return userString.replace("!", " ").replace("?", " ").replace(".", " ").split()
print(map(lambda x:x.capitalize, getSplit("sdfsdf! sdfsdfdf? sdfsfdsf.sdfsdfsd!fdfgdfg?dsfdsfgf")))
Normally, you could use re.split(), but since you cannot import anything, the best option would be just to do a for loop. Here it is:
def getSplit(user_input):
n = len(user_input)
sentences =[]
previdx = 0
for i in range(n - 1):
if(user_input[i:i+2] in ['. ', '! ', '? ']):
sentences.append(user_input[previdx:i+2].capitalize())
previdx = i + 2
sentences.append(user_input[previdx:n].capitalize())
return "".join(sentences)
I would split the string at each white space. Then scan the list for words that contain the special character. If any is present, the next word is capitalised. Join the list back at the end. Of course, this assumes that there are no more than two consecutive spaces between words.
def capitalise(text):
words = text.split()
new_words = [words[0].capitalize()]
i = 1
while i < len(words) - 1:
new_words.append(words[i])
if "." in words[i] or "!" in words[i] or "?" in words[i]:
i += 1
new_words.append(words[i].capitalize())
i += 1
return " ".join(new_words)
If you can use the re module which is available by default in python, this is how you could do it:
import re
a = 'test this. and that, and maybe something else?even without space. or with multiple.\nor line breaks.'
print(re.sub(r'[.!?]\s*\w', lambda x: x.group(0).upper(), a))
Would lead to:
test this. And that, and maybe something else?Even without space. Or with multiple.\nOr line breaks.

Python 3, receive a string as an argument without any return value

I'm learning Python and have been taking an online class. This class was very basic and I am know trying to continue my studies elsewhere. Stackoverflow.com has helped me a great deal. In the online course we didn't cover a lot about return statements, which I am now trying to learn. I would like to do something very basic, so I was thinking of creating a program that would receive a string as an argument without having any return value. I want the user to type a word that will be shown with characters or symbols between every letter.
Example
User types in the word Python.
The word will be shown as =P=y=t=h=o=n= or -P-y-t-h-o-n- or maybe with * between every letter.
Is this an easy task? Can someone help me how to go about doing this?
Thank you.
Joel
If you want to do it yourself, you can go through your string like this:
my_string = "Python"
for letter in my_string:
# do something with the letter
print(letter)
This will print each letter in your word. What you want to do is having a new string with your desired character. You probably know you can concatenate (append) two strings in this way :
str1 = "hello"
str2 = "world"
str3 = str1 + str2
print(str3) #helloworld
So to do what you'd like to do, you can see each letter as a substring of your main string, and your desired character (for example *) as another string, and build a result string in that way.
inputString = "Python"
result = ""
myChar = "*"
for letter in inputString:
# build your result
build = build + letter
print(build)
This will just copy inputString into result, though I think you'll have understood how to use it in order to add your custom chars between the letters.
Yes python makes this sort of string manipulation very easy (some other languages... not so much). Look up the standard join function in the python docs.
def fancy_print(s, join_char='-'):
# split string into a list of characters
letters = list(s)
# create joined string
output = join_char + join_char.join(letters) + join_char
# show it
print(output)
then
>>> fancy_print("PYTHON")
-P-Y-T-H-O-N-
>>> fancy_print("PYTHON", "*")
*P*Y*T*H*O*N*

How to split up a long list using \n

Here is a long string that I convert to a list so I can manipulate it, and then join it back together. I am having some trouble being able to have an iterator go through the list and when the iterator reach, let us say every 5th object, it should insert a '\n' right there. Here is an example:
string = "Hello my name is Josh I like pizza and python I need this string to be really really long"
string = string.split()
# do the magic here
string = ' '.join(string)
print(string)
Output:
Hello my name is Josh
I like pizza and python
I need this string to
be really really long
Any idea how i can achieve this?
I tried using:
for words in string:
if words % 5 == 0:
string.append('\n')
but it doesn't work. What am I missing?
What you're doing wrong is attempting to change string in your example which doesn't affect the string contained in your list... instead you need to index into the list and directly change the element.
text = "Hello my name is Josh I like pizza and python I need this string to be really really long"
words = text.split()
for wordno in range(len(words)):
if wordno and wordno % 5 == 0:
words[wordno] += '\n'
print ' '.join(words)
You don't want to call something string as it's a builtin module that is sometimes used and may confuse things, and I've also checked that wordno isn't 0 else you'll end up with a single word line in your rejoin...
The problem with the for loop you attempted to use, is that it didn't keep the index of the word, and thus could not determine which word that was the 5th. By using enumerate(iterable) you can get the index of the word, and the word at the same time. You could also just use range(len(iterable)) to get the index and just do it the same way.
string = "Hello my name is Josh I like pizza and python I need this string to be really really long"
string = string.split()
for word_num, word in enumerate(string):
if word_num and word_num % 5 == 0:
# access the array since changing only the variable word wont work
string[word_num] += '\n'
string = ' '.join(string)
print(string)
Edit:
As #JonClements pointed out, this causes "Hello" to be printed on its own line, because 0%5 = 0. Therefore I added a check to see if word_num evaluates to True (which it does if it is not equal to 0)
In this case you should probably be creating a new string instead of trying to modify the existing one. You can just use a counter to determine which word you're on. Here's a very simple solution, though Jon Clements has a more sophisticated (and probably more efficient) one:
newstring = ""
str = "Hello my name is Josh I like pizza and python I need this string to be really really long"
strlist = str.split()
for i, words in enumerate(strlist):
newstring += words
if (i + 1) % 5 == 0:
newstring += "\n"
else:
newstring += " "
`enumerate1 returns both the index of the word in your list of words, as well as the word itself. It's a handy automated counter to determine which word you're on.
Also, don't actually name your string string. That's the name of a module that you don't want to overwrite.
I am sure this could be much shorter but this does what you want. They key improvements are a new string to hold everything and the use of enumerate to catch the ith word in the list.
string = "Hello my name is Josh I like pizza and python I need this string to be really really long"
string2 = ""
for (i,word) in enumerate(string.split()):
string2 = string2 + " " + word
if (i + 1) % 5 == 0:
string2 = string2 + '\n'
print(string2)
you can use enumerate() on your string after you split it.
and iterate like that:
new_string_list = []
for index, word in string:
if (index + 1) % 5 == 0:
word += '\n'
new_string_list.append(word)
string = ' '.join(new_string_list)
Use enumerate to get index and % operation on i to append '\n' every n blocks
new_string_list = []
strlist = oldstr.split()
// do magic here
for i,word in enumerate(strlist):
new_string_list.append(word) #it is better
#to append to list then join, using + to concatenate strings is ineffecient
if count % 5 == 0:
new_string_list.append('\n')
print("".join(new_string_list))
Using list slicing...
s='hello my name is josh i like pizza and python i need this string to be really really long'
l=s.split()
l[4::5]=[v+'\n' for v in l[4::5] ]
print '\n'.join(' '.join(l).split('\n '))
hello my name is josh
i like pizza and python
i need this string to
be really really long
Horrible one-liner I cooked up as an example of what you should never do.
s='hello my name is josh i like pizza and python i need this string to be really really long'
print '\n'.join([' '.join(l) for l in [s.split()[i:i + 4] for i in range(0, len(s.split()), 4)]])

Categories