I'm trying to make a program using python for class that works like this:
'Enter a word: " (EG Stack)
Then it outputs
S
St
Sta
Stac
Stack
I believe that it would use a looping function, but I'm completely stuck!
You can use slicing to achieve your output. Each iteration of the for loop increments an index variable (i below), and this is used to display ever increasing slices from the string.
>>> word = 'Stack'
>>> for i in range(1, len(word)+1):
... print word[:i]
...
S
St
Sta
Stac
Stack
>>> word='Slicing'
>>> for i in range(1, len(word)+1):
... print word[:i]
...
S
Sl
Sli
Slic
Slici
Slicin
Slicing
You can read about slicing in the Python tutorial.
msg = raw_input("Enter a word: ") #raw_input will convert the input into a string
#otherwise it would crash without quotation marks
word = "" #Initialize a variable
for letter in msg: #Cycle through each letter
word += letter #Adds that letter to your string
print(word) #Prints out the current letters
http://pastebin.com/CDzNfdbJ
Got it, I don't really understand it, but it works.
Related
I'm trying to make a project in python so that whenever the program encounters a capital letter it makes a white space. So for example "helloThisIsMyProject" > hello This is My Project.
def project(w):
lst = []
for i in w:
lst.append(i)
for letter in lst:
if letter.isupper():
index = lst.index(letter)
lst.insert(index, " ")
continue
return "".join(lst)
print(project("helloThisIsMyProject"))
I'm having a problem with insert() and the for loop because the for loop is endlessly looping over the "T" from "This". I tried using continue to skip the letter T but it didn't fix my problem.
Those 1st three lines are simply
lst = list(w)
But you would find this more convenient:
lst = []
for letter in w:
if letter.isupper():
lst.append(" ")
lst.append(letter)
That is, rather than producing a list and going back to fix it up,
you could have it correct from the outset.
You can conditionally output a SPACE before you output the letter.
If you prefer to do it with a list comprehension,
you might enlist the aid of a helper:
def adjust(s: str) -> str:
"""Returns the input string, possibly whitespace adjusted."""
return " " + s if s.isupper() else s
lst = [adjust(letter)
for letter in w]
or more compactly:
lst = list(map(adjust, w))
You could use a join with a list comprehension that adds the space to individual characters:
def spaceCaps(w):
return "".join(" "*c.isupper()+c for c in w)
spaceCaps("helloThisIsMyProject")
'hello This Is My Project'
You could also use the sub() function from the regular expression module:
import re
def spaceCaps(w):
return re.sub("([A-Z])",r" \1",w)
I am trying to make a program that asks for a word, and then prints it to the console multiple times, each time removing the first character until the word ends. Program also asks if the word should be printed as shown or backwards.
The printing action is the same regardless if the word should be printed forwards or backwards.
The output should be something like this:
Give a word: milkfloat
Print forward? (yes/no): yes
milkfloat
ilkfloat
lkfloat
kfloat
float
loat
oat
at
t
Give a word: hippopotamus
Print forward? (yes/no): no
sumatopoppih
umatopoppih
matopoppih
atopoppih
topoppih
opoppih
poppih
oppih
ppih
pih
ih
h
I am trying but I cant figure out how to do it. Can anybody help?
Use the input() function to get some input from the command line e.g.
word = input('Enter word: ')
print(word)
>>> Enter word:
>>> Enter word: dog
>>> 'dog'
Use the print() function to print strings e.g.
word = 'dog'
print(word)
>>> 'dog'
Use an if statement to evaluate a condition e.g.
word = 'dog'
if word == 'dog':
print('I love dogs!')
elif word == 'cat':
print('I am more of a dog person...')
else:
print('Do you not like animals?')
>>> I love dogs!
Use [] square brackets to slice strings into the pieces you want e.g.
word = 'dog'
print(word[:-1])
>>> 'do'
print(word[1:])
>>> 'og'
Use the len() function to work out the length of a string e.g.
word = 'dog'
print(len(word))
>>> 3
Use a for loop with range() to do something a certain number of times e.g.
for i in range(3):
print(i)
>>> 0
>>> 1
>>> 2
I'll leave the rest to you.
def printer(word):
for i in range(len(word)):
print(word[i::])
text = input("Give a word: ")
forward = input("Print forward? (yes/no): ")
if forward=="yes":
printer(text)
else:
printer(text[::-1])
So this is something that I've set a friend to do as an exercise to get more comfortable with python.
The exercise is called "word pyramids" and this is the answer that I came up with (so that they have something to refer to later if they get stuck):
def print_backwards_word_pyramid(word):
for i in range(0, len(word)):
if i == 0:
print(word[::-1])
else:
print(word[:i-1:-1])
return
and this will print, for the word "juice"
eciuj
eciu
eci
ec
e
But, if you want something a little bit more elegant, the back half can be done as:
def print_backwards_word_pyramid(word):
for i in range(0, len(word)):
print(word[i:][::-1])
return
... which if read from right to left (for those who need a hand with what this is telling python) says:
In reverse, the slice starting at the "i'th" character, of the string value of variable "word", print.
I have a program that counts and prints all words in a sentence that contains a specific character(ignoring case).
Code in Python -
item=input()
ip=input().tolower()
r=ip.count(item)
print(r)
ip=ip.split()
for word in ip:
if item in word:
print((word), end=' ')
This program works as expected but for the last word that is printed I don't want a white-space after it.
If anyone could guide me on how to remove the space it would be appreciated.
Why don't you use list comprehension and str.join?
print(' '.join([w for w in ip if item in w]))
I don't think there's a way to remove that, as it's a part of your terminal. Best answer I can give you.
I expanded on the code though, cause I was kinda bored.
sentence = input("Enter a sentence: ").lower()
pull = input("Which character(s) do you want to count?: ").lower()
for c in pull:
occurrences = 0
for character in sentence:
if c == character:
occurrences+=1
if c!=" ": print("\'%s\' appears %d times"%(c, occurrences))
for word in sentence.split():
occurrences = 0
for character in word:
if c == character:
occurrences+=1
if occurrences == 1:
print(("1 time in \'%s\'")%(word))
elif occurrences > 0:
print(("%d times in \'%s\'")%(occurrences,word))
+The solution with a list comprehension appears more concise, but if you prefer an alternative you can use the following. It was tested and worked with the example in the picture.
# Amended solution. The commented lines are the amendment.
item = input('Letter: ')
ip = input('Input: ').lower()
r = ip.count(item)
print(r)
ip = ip.split()
outputString = '' # Added: Initialise an empty string to keep the answer
for word in ip:
if item in word:
outputString += word + ' ' # Changed: Accumulates the answer in a string
print(outputString[:-1]) # Added: Prints all the string's characters
# except the last one, which is the additional space
You're close, just change your print statement from print((word), end=' ') to print((word), end=''). Your print statement has a whitespace for the end but you don't want the whitespace so make the end an empty string.
This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I'm new to coding, and I found this exercise problem in a Python practice website. The instructions go like this:
"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
So I inputted this code:
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter)
else:
print(letter+'o'+letter)
print(translate('this is fun'))
and I got this:
tot
hoh
i
sos
o
i
sos
o
fof
u
non
None
So how do I put all these strings in one line? I've been scratching my head for so long. Please help and thank you:)
You can concatenate the strings iteratively. You should include a whitespace as part of the characters to exclude to avoid putting an 'o' in between whitespaces.
def translate(string):
notconsonant = ['a','e','i','o','u', ' ']
s = ''
for letter in string:
if letter in notconsonant:
s += letter
else:
s += letter+'o'+letter
return s
Or use join with a generator expression that returns the right letter combination via a ternary operator:
def translate(string):
notconsonant = {'a','e','i','o','u', ' '}
return ''.join(letter if letter in notconsonant else letter+'o'+letter for letter in string)
Note that you can speed up the lookup of letters that are not consonants if you made the list a set, as membership check for sets is relatively faster.
>>> translate('this is fun')
'tothohisos isos fofunon'
Just use the end parameter in print function. (I assumed that you are using python 3.x, with print being a function)
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter, end='')
else:
print(letter+'o'+letter, end='')
print(translate('this is fun'))
Try to append it in a temporary string and to print it at the end ;)
print get's you to a new line. Use a concatenation and a new string instead (here the new string is called result) :
def translate(string):
vowels=['a','e','i','o','u']
# Use a new variable :
result = ''
for letter in string:
if letter in vowels:
result = result + letter
else:
result = result + letter + 'o' + letter
return result
print(translate('this is fun'))
I've made a simple script in python which shifts the letters up 5 spaces in the ASCII table using chr and ord. See below:
word = "python"
print 'Shifted 5 letters are: '
for letters in word:
print chr(ord(letters)+5),
The output is:
Shifted 5 letters is:
u ~ y m t s
The output is great, but how do I stop the for loop putting spaces in-between each letter?
If you don't need to use the for loop, simply do this:
print ''.join([chr(ord(letter) + 5) for letter in word])
instead of the whole loop.
There is no way to stop Python 2.x's print statement from printing a space when you use the "magic comma".
This is part of the reason Python 3.x's print function is more flexible, using keyword arguments instead of magic syntax:
for letters in word:
print(chr(ord(letters)+5), end='')
If you really want to, you can get the same behavior in Python 2.x with from __future__ import print_function (or by using the third-party six library).
However, usually, when you're having problem fighting with print to do what you want, the solution is to format your string first, then print it. So:
output = ''
for letters in word:
output += chr(ord(letters)+5)
print output
It's generally more pythonic (and faster) to build up a list of strings, and calling join at the end, instead of repeatedly appending to a string:
output = []
for letters in word:
output.append(chr(ord(letters)+5))
print ''.join(output)
And you can make that simpler (and even more fasterer) by turning the loop into a comprehension instead of a statement:
print ''.join(chr(ord(letters) + 5) for letters in word)
I don't know if I get what you're asking 100 % but this work-around returned the letters without any whitespace :
def no_space(word) :
new_word = ""
for letter in word :
new_word += chr(ord(letter) + 5)
return new_word
Then call the function :
no_space("python")
Result : 'u~ymts'