I am currently trying out Python. I was trying to print out an upside-down pyramid. I'm making the pyramid out of *s and in each line, I have to delete a certain amount of *s from the line. This is my
space = ""
astr3 = "**********"
placeholder2 = 1
while placeholder2 < 10:
print (space, astr3, "\n")
space += " "
astr3 = "*********" #this is supposed to be subtraction
placeholder2 += 1
Please tell if there is any way to delete strings from strings.
You can use list slicing to slice Strings/Lists. Check it out. You don't need \n in the print statement as it adds a newline. To make a pyramid using your logic, you can delete two * from the string and then print. Remember, it's always better to use intuitive names for the variables. Eg: you can use, idx for index instead of placeholder2.
# Program to print an upside down pyramid
space = ""
astr3 = "**********"
num_stars = len(astr3) # len(astr3) gives number of * in the astr3 string
placeholder2 = 1
while placeholder2 < num_stars // 2:
display_str = space + astr3 # Adding strings is called concatnation.
print(display_str) # This will not add additional space between spaces and astr3
space += " "
astr3 = astr3[:-1] # deleting the last element from the list. Called list slicing
astr3 = astr3[1:] # deleting the first element from the list. Called list slicing
placeholder2 += 1
The above code outputs the following:
**********
********
******
****
**
TIP: It's better to share the expected output in the question so that the community can help.
Initialize placeholder2 with 0 to get the pyramid from the original string to 1 length string. Since your requirements were to remove the string 1 by per line. To do it set the condition astr3[:-1] and put it to the same variable.
space = ""
astr3 = "**********"
placeholder2 = 0
while placeholder2 < 10:
print(space, astr3)
space += " "
astr3 = astr3[:-1]
placeholder2 += 1
Output
**********
*********
********
*******
******
*****
****
***
**
*
Thank you guys for all the help! I took what you guys said and made the pyramid :D (although my code is very very dumbed down). Here is the code:
space1 = ""
astr4 = "**********"
placeholder3 = 1
while placeholder3 < 7:
if placeholder3 == 6:
print (space1, "*")
print(space1, astr4)
astr4 = astr4[1:]
astr4 = astr4[:-1]
space1 += " "
placeholder3 += 1
Related
I need to move a whitespace in a string one position to the right.
This is my code:
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:]
E.g.:
If resultaat =
"TH EZE NO FPYTHON."
Than my output needs to be:
'THE ZEN OF PYTHON.'
, but the output that I get is:
"TH EZE NO F PYTHON."
I think this happened because the loop undid the action where it moved the previous space.
I don't know how to fix this problem.
Can someone help me with this?
Thanks!
Each time through the loop you're getting slices of the original resultaat string, without the changes you've made for previous iterations.
You should copy resultaat to string first, then use that as the source of each slice so you accumulate all the changes.
string = resultaat
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = string[:i] + string[i+1] + " " + string[i+2:]
You could do something like this:
# first get the indexes that the character you want to merge
indexes = [i for i, c in enumerate(resultaat) if c == ' ']
for i in indexes: # go through those indexes and swap the characters as you have done
resultaat = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:] # updating resultaat each time you want to swap characters
Assuming the stated input value actually has one more space than is actually needed then:
TXT = "TH EZE NO FPYTHON."
def process(s):
t = list(s)
for i, c in enumerate(t[:-1]):
if c == ' ':
t[i+1], t[i] = ' ', t[i+1]
return ''.join(t)
print(process(TXT))
Output:
THE ZEN OF PYTHON.
I have a task to create a row of numbers. what I have now works and prints on one line. I want to try to use it without end. What I've tried already is creating a variable new_line = "" and adding that / equaling that to the string in the print line. I also need to be able to print another "|" at the end of the string only and I can't do that with end.
def print_row(n, max_power, column_width):
count = 0
exponent = max_power
max_power = 0
while count < exponent:
max_power = max_power + 1
value = power(n, max_power)
print("|",padded(value, column_width),end='')
count = count + 1
You're using the loop to control the wrong thing. Use the loop to build a list of values to be combined using | as a separator, then print that string with one call to print.
def print_row(n, max_power, column_width):
values = [padded(power(n, p), column_width) for p in range(max_power)]
print("|" + "|".join(values), end="|")
The initial "|" can be added to the value to actually print (as shown), or could be output with a preceding call to print("|", end='').
A string is given in which there are no beginning and ending spaces. It is necessary to change it so that the length of the string becomes equal to the specified length, greater than the current length of the string. This should be done by inserting additional spaces between the words. The number of spaces between individual words should not differ by more than one space (that is, spaces are added evenly).
The string itself is entered by the user from the keyboard. The teacher said that I need to solve the problem using slices, but I don't understand exactly how. The problem is that it is not known in advance how long the entered string will be. And how many initial gaps there will be in it. At the same time, it is necessary that the length of the final line exactly matches the length that the user entered.
Here's what I've come up with so far. This code evenly adds spaces to the beginning and end of the entered line, if there were no spaces in it initially.
line_0 = input('Enter the required line:\n')
print('Current string length:\n', len(line_0), sep = '')
num_0 = len(line_0)
num_1 = int(input('Enter the total length of the string:\n'))
num_d = num_1 - num_0
s = line_0.count(' ')
line_1 = ''
if s == 0:
if (num_d % 2) != 0:
cup_1 = ' ' * (num_d // 2 + 1)
cup_2 = ' ' * (num_d // 2)
line_1 = cup_1 + line_0 + cup_2
else:
cup_1 = ' ' * (num_d // 2)
line_1 = cup_1 + line_0 + cup_1
print("'^' - the beginning and end of the line (not included in the
length of the final line).")
print('The resulting string is long ', len(line_1), ':\n', '^', line_1,
'^', sep = '')
First you need to figure how many spaces you will have to add.
In the same time, you'll split the initial string in a list of words.
Than, you calculate the minimum amount of spaces to add to each word, and the remaining that you'll add to the n first words.
Finally you add the spaces and maxe the words and spaces a str.
initial_sentence = "Lorem ipsum dolor sit amet"
spaces_to_add = int(input("Length needed : ")) - len(initial_sentence)
words = initial_sentence.split(" ")
number_words = len(words) - 1
min_spaces_added = spaces_to_add // number_words
spaces_remaining = spaces_to_add % number_words
final_string = ""
for word_ID in range(number_words) :
final_string = final_string + words[word_ID] + " "*(1+min_spaces_added) #the initial space after the word that has been removed by the .split() + the minimum required
if word_ID+1 <= spaces_remaining :
final_string += " "
final_string += words[-1]#the last word
print(final_string)
I'm writing a program that takes two inputs, number of lines and number of cheers as input. The number of lines is how many lines the user wants to print out and the number of cheers are in the format that 1 cheer is the word "GO" and two cheers are two "GO" s ...and their is the word "BUDDY" within two neighboring GO's. And each new line has to be indented 3 spaces more then the one before. And this is the program I've come up with:
lines = input("Lines= ")
cheers = input("Cheers= ")
if cheers == 1:
i = 1
space = 0
S = ""
while i<=lines:
S=S+(" "*space)+"GO \n"
i += 1
space+=3
print S
else:
n = 1
cheer1 = "GO BUDDY "
cheer2 = "GO"
space = 0
while n<= cheers:
print (" "*space)+(cheer1*cheers)+cheer2
space+=3
n += 1
But the problem with this is that it doesn't print out the right number of GO's in the number of cheers. How can I modify my code to fix this problem? This is the output format I want to get :
Often in Python you don't need any loops
lines = int(input('Lines= '))
cheers = int(input('Cheers= '))
line = ' BUDDY '.join(['GO']*cheers)
for i in range(cheers):
print(' '*(i*3) + line)
def greet(lines, cheers):
i = 0
line_str = ""
while i < cheers: # Build the line string
i += 1
line_str += "GO" if i == cheers else "GO BUDDY "
i = 0
while i < lines: #Print each line
print(" "*(i*3) + line_str)
i += 1
greet(2,1)
greet(4,3)
greet(2,4)
Try this.
def greet(lines, cheers):
for i in range (lines):
output = (" ") * i + "Go"
for j in range (cheers):
if cheers == 1:
print output
break
output += "Budddy Go"
print output
Hope this helps.
I'm trying to create a iso triangle (one that starts in the middle).
I have a code but the problem is that I'm not allowed to use Y* "*" 5 in my code.
(The y is a variable there)
Also I may only use one print statement at the end of my code.
Can you please help me out.
f = int(raw_input("enter"))
for i in range(f):
print " " * (f-i-1) + "*" * (2*i+1)
creats this triangle
*
***
*****
*******
*********
***********
However, you are not allowed to use the *-operator on string and int. So for example ''***'' * 3 is not allowed, but 3 * 4 is
This just creates a continuous string and then prints it at the end
f = int(raw_input("Enter height: "))
s = ''
for i in xrange(f):
for j in xrange(f-i-1):
s += ' '
for j in xrange(2*i+1):
s += '*'
s += '\n'
print s
This is a solution which i think is very easy to understand. You can make the parameter of range() variable, to make it more dynamic.
from __future__ import print_function
for i in range(1,12,2):
count=(11-i)/2
for j in xrange(count):
print(" ",end='')
for j in xrange(i):
print("*",end='')
for j in xrange(count):
print(" ",end='')
print(end="\n")
I think the best solution is using the center() string method:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
star += "**" if X>0 else ""
full_string += star.center(2*f-1) + "\n"
print full_string[:-1]
The str.center() documentation:
https://docs.python.org/2/library/string.html#string.center
EDIT: If you can't use the print statement within the for loop, you could concatenate the string during the loop and print it at the end:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
# the first row should take only one star
star += "**" if X>0 else ""
star2 = star.center(2*f-1)
full_string += star2 + "\n"
# slice the string to delete the last "\n"
print full_string[:-1]
I noticed that using a for loop add a newline character. If you want to avoid this, you can slice the string before printing.
There is no problem with this code, i just checked it and it worked fine. If you would post the error message we might be able to help a bit more.