How to separate strings multiplied by integer in Python? - python

Let's say we have a text "Welcome to India". And I want to multiply this string with 3, but to appear with comma delimitation, like "Welcome to India, Welcome to India, Welcome to India". The thing is I know this piece of code could work:
a = 'Welcome to India'
required = a * 3 # but this code is not comma-delimited.
Also, this piece of code doesn't work as well
required = (a + ", ") * 3 # because it puts comma even at the end of the string
How to solve this problem?

", ".join(["Welcome to India"]*3)

Based on the part of your code that you say doesn't work well because it adds a comma to the end, you can modify it like this:
required = (a + ", ") * 2 + a
Or if you don't like it, you can use sum instead of multiply, it's not the optimal way, for sure, but it will work:
a = 'Welcome to India'
required = a + ", " + a + ", " + a

Define Function and you can use it.
def commaFunc(value, count):
buffer = []
for x in range(count):
buffer[x] = value
return ",".join(buffer)

Related

4.16 LAB: Warm up: Drawing a right triangle

This program will output a right triangle based on user specified height triangle_height and symbol triangle_char.
(1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character.
(2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches triangle_height. Output a space after each user-specified character, including a line's last user-specified character.
I'm having trouble figuring out how to create a space between my characters. Example input is % and 5. My code is:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range (triangle_height):
print((triangle_char) * (i + 1))
my output is:
%
%%
%%%
%%%%
%%%%%
while expected output is:
%
% %
% % %
% % % %
% % % % %
You need to use join(). This would work:
for i in range(triangle_height):
print(' '.join(triangle_char * (i + 1)))
It is adding spaces between every character because strings are iterable.
This may be optimized a bit by having a list of the characters and appending 1 character in each iteration, rather than constructing triangle_char * (i+1) every time.
This should fix the white space errors:
for i in range(triangle_height):
print(' '.join(triangle_char * (i + 1)) + ' ')
for i in range(triangle_height+1):
print(f'{triangle_char} '*i)
I see the popular way so far is using join, but another way while trying to stay true to the original idea is you simply can add a white space after each character. See below:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range(triangle_height):
print((triangle_char + ' ') * (i + 1))
There are some really good suggestions on here. Another approach is to use an incremented variable in a while loop as shown below:
triangle_char = input("Enter a character:\n")[0]
triangle_height = int(input("Enter triangle height:\n"))
i = 0
while (i <= triangle_height):
print((triangle_char + ' ') * i)
i += 1
With the example above, i iterates until it is equal to triangle_height and uses polymorphism to generate a quantity of (triangle_height + ' ') based on the value of i. This will generate the right triangle this lab requires. The space is used to format the triangle per lab requirements.
Another method is using the .join() feature, and it certainly would work well here, but is not taught until CH7 of this book where you learn about input and CSV files. I am unsure if your professor would approve of using this, and I am only saying this because my professor was strict about using material not covered.
An additional method mentioned already is to use a for loop with the use of the range() feature containing an expression:
triangle_char = input("Enter a character:\n")[0]
triangle_height = int(input("Enter triangle height:\n"))
for i in range((triangle_height + 1)):
print((triangle_char + ' ') * i)
The end point of range() being just triangle_height would not suffice because the value specified as the end point is not included in the sequence. This would make a right triangle with a height of 4 even if triangle_height was 5 Therefore, you must use the expression (triangle_height + 1). From there, the output is set up similarly to my first solution.
Try adding a whitespace in the print statement.
height = int(input())
symbol = (input())
print()
for i in range(height): #Loop for every index in the range 0-height
print((symbol + ' ') * (i + 1)) #Add whitespace to symbol

Making triangles in Python

Below is a code I made in Python for our lab activity which makes a triangle.
side = input("Input side: ")
def triangle(x):
print ((x - 1)*" "),"*"
asterisk = "*"
space = side
for i in range(x):
asterisk = "**" + asterisk
space = (space-1) * " "
print space,asterisk
triangle(side)
The output should be this:
*
***
*****
I got the number of asterisks on each row correctly, but I cannot figure out how to make the necessary amount of spaces to make it look like a triangle. Using the above code, which I think might be the solution, always produces an error at line 9. Any help I appreciated. (I'm new here so if I violated some rules please let me know.) Thanks and good day!
You are getting the error(TypeError) because you are assigning the space variable with a string type, and then you are subtracting it in the next loop. Edited code would look like this (In python 2.7) and Never mix 4 spaces and 8 spaces indentation.
side = input("Input side: ")
def triangle(x):
print ((x)*" "),"*"
asterisk = "*"
spaces = side
for i in range(x):
asterisk = "**" + asterisk
spaces -= 1
print ' ' * spaces,
print asterisk
triangle(side)
I write a new one in python3.5,And it may be suit for you.But it is not prefect
side = 4
def triangle(x):
for y in range(1,x):
s = 2*y - 1
b = x - y
print(" "*b+"*"*s)
triangle(side)
Output:
*
***
*****
Here is the code to have an isosceles triangle:
def print_triangle(n):
for i in range(1, n+1):
print (" "*(n-i), end=" ")
print (("*"*i)+(i*"*"))
print(print_triangle(6))
Output:
**
****
******
********
**********
************
None

Python Printing and multiplying strings in Print statement

I am trying to write a simple python program that prints two ##, then # #, and increases the number of spaces in between the #'s each time. Here is the code I tried:
i=0
while (i<=5):
print ("#" (" " * i) "#")
#print (" " * i)
#print ("#" "#")
The multiplication works in the first line of code I tested then commended out, I see it in the shell each time it prints one more space.
Printing two #'s works also.
I can't figure out how to combine it into one statement that works, or any other method of doing this.
Any help would be appreciated, thanks.
i=0
while (i<=5):
print( "#" +(" "*i)+ "#")
i=i+1
You need to add the strings inside the print statement and increment i.
You want to print a string that depends an a variable. There are other methods to build a string but the simplest, most obvious one is adding together some fixed pieces and some computed pieces, in your case a "#", a sequence of spaces and another "#". To add together the pieces you have to use the + operator, like in "#"+" "+"#".
Another problem in your code is the while loop, if you don't increment the variable i its value will be always 0 and the loop will be executed forever!
Eventually you will learn that the idiom to iterate over a sequence of integers, from 0 to n-1 is for i in range(n): ..., but for now the while loop is good enough.
This should do it:
i=0
while (i<=5):
print ('#' + i * ' ' + '#')
i = i + 1
Try this:
def test(self, number: int):
for i in range (number)):
print('#' +i * ''+ '#')
i+=1
return

Printing Out Every Third Letter Python

I'm using Grok Learning and the task it give you is 'to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.'
This is my code:
text = input("Message? ")
length = len(text)
for i in range (0, length, 3):
decoded = text[i]
print(decoded, end=" ")
Although I it says it isn't correct, it say this is the desired out-put:
Message? cxohawalkldflghemwnsegfaeap
c h a l l e n g e
And my output is the same expect, in my output, I have a space after the last 'e' in challenge. Can anyone think of a way to fix this?
To have spaces only between the characters, you could use a slice to create the string "challenge" then use str.join to add the spaces:
" ".join(text[::3])
Here's Grok's explanation to your question: "So, this question is asking you to loop over a string, and print out every third letter. The easiest way to do this is to use for and range, letting range do all the heavy lifting and hard work! We know that range creates a list of numbers, - we can use these numbers as indexes for the message!"
So if you are going to include functions like print, len, end, range, input, for and in functions, your code should look somewhat similar to this:
line = input('Message? ')
result = line[0]
for i in range(3, len(line), 3):
result += ' ' + line[i]
print(result)
Or this:
line = input('Message? ')
print(line[0], end='')
for i in range(3, len(line), 3):
print(' ' + line[i], end='')
print()
Or maybe this:
code = input ('Message? ') [0::3]
msg = ""
for i in code: msg += " " + i
print (msg [1:])
All of these should work, and I hope this answers your question.
I think Grok is just really picky about the details. (It's also case sensitive)
Maybe try this for an alternative because this one worked for me:
message = input('Message? ')
last_index = len(message) -1
decoded = ''
for i in range(0, last_index, 3):
decoded += message[i] + ' '
print(decoded.rstrip())
You should take another look at the notes on this page about building up a string, and then printing it out all at once, in this case perhaps using rstrip() or output[:-1] to leave off the space on the far right.
Here's an example printing out the numbers 0 to 9 in the same fashion, using both rstrip and slicing.
output = ""
for i in range(10):
output = output + str(i) + ' '
print(output[:-1])
print(output.rstrip())
If you look through the Grok course, there is one page called ‘Step by step, side by side’ (link here at https://groklearning.com/learn/intro-python-1/repeating-things/8/) where it introduces the rstrip function. If you write print(output.rstrip()) it will get rid of whitespace to the right of the string.

python string input problem with whitespace!

my input is something like this
23 + 45 = astart
for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this
SyntaxError: invalid syntax
the code is this
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
its always number + number = astar
its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error
Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing
on either side of the + and = in the code and input.
You appear to have two spaces on either side of them in the code, but only one on either
side in the input. Also - you do not have to use the str(i) in a generator. You can do
it like a,b=k.split(' + ')
My cut and pastes:
My test script:
print 'Enter input #1:'
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
print 'Here are the resulting values:'
print a
print b
print c
print 'Enter input #2:'
k=raw_input()
a,b=k.split(' + ')
b,c=b.split(' = ')
print 'Here are the resulting values:'
print a
print b
print c
From the interpreter:
>>>
Enter input #1:
23 + 45 = astart
Here are the resulting values:
23
45
astart
Enter input #2:
23 + 45 = astart
Here are the resulting values:
23
45
astart
>>>
Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs
calling (... for ...) only returns a generator object, not a tuple
try one of the following:
a,b=[str(i) for i in k.split(' + ')]
a,b=list(str(i) for i in k.split(' + '))
they return a list which can be unpacked (assuming one split)
or use str.partition assuming 2.5 or greater:
a, serperator, b = k.partition('+')
which will always return a 3 tuple even if the string isn't found
Edit: and if you don't want the spaces in your input use the strip function
a = a.strip()
b = b.strip()
Edit: fixed str.partition method, had wrong function name for some reason
I think I'd just use a simple regular expression:
# Set up a few regular expressions
parser = re.compile("(\d+)\+(\d+)=(.+)")
spaces = re.compile("\s+")
# Grab input
input = raw_input()
# Remove all whitespace
input = spaces.sub('',input)
# Parse away
num1, num2, result = m.match(input)
You could just use:
a, b, c = raw_input().replace('+',' ').replace('=', ' ').split()
Or [Edited to add] - here's another one that avoids creating the extra intermediate strings:
a, b, c = raw_input().split()[::2]
Hrm - just realized that second one requires spaces, though, so not as good.
Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products.
k=raw_input()
print k.split(' + ')
a,b=(str(i) for i in k.split(' + '))
print b.split(' = ')
b,c=(str(i) for i in b.split(' = '))
This will show you the actual list elements produced by the split, which might shed some light on the problem you're having.
I'm not normally a fan of debugging by print statement, but one of the advantages that Python has is that it's so easy to fire up the interpreter and just mess around interactively, one statement at a time, to see what's going on.

Categories