How can I remove the hyphen at the end? - python

Heres my code
#!/usr/bin/env python
s = raw_input()
n = input()
x = (s + " ") * n
def remove(x):
return x.replace(" ","-")
print remove(x)
Basically its like this
s = abc
n = 2
I want to print abc-abc
but I end up getting abc-abc-
don't know how to do this.

n = input()
x = (s + " ") * n
Assuming you enter 'abc' and '2', the string becomes 'abc abc ' (Note the space at the end). When you replace with -, it replaces the trailing space with a -. A very quick solution would be to use
x.replace(" ", "-", n-1)
The third parameter is the count, so it will replace all but the trailing space.

This code will do the job
'-'.join([s]*n)
for your data it will be abc-abc

How about this solution:
#!/usr/bin/env python
s = raw_input()
n = input()
x = (s + " ") * (n-1)
x += s
def remove(x):
return x.replace(" ","-")
print remove(x)
So the last 's' would not add any space to x and therefor there is no space at the end to turn into a hyphen.

Related

how to I make the code to print the numbers given and and show what it equals

I tried to make just add print(a+b) and I only got what it equals I don't know what to do I can't find it or look for it online.
You are mixing up printing a string vs. printing an expression.
Printing a string like print('hello world') will print the literal message because you've indicated it's a string with quotes.
However, if you provide an expression like print(a+b), it will evaluate that expression (calculate the math) and then print the string representation of that evaluation.
Now, what you want is actually a mix of both, you want to print a string that has certain parts replaced with an expression. This can be done by "adding" strings and expressions together like so:
print(a + '+' + b + '=' + (a+b))
Notice the difference between + without quotes and '+' with quotes. The first is the addition operator, the second is the literal plus character. Let's break down how the print statement parses this. Let's say we have a = 5 and b = 3. First, we evaluate all the expressions:
print(5 + '+' + 3 + '=' + 8)
Now, we have to add a combination of numbers with strings. The + operator acts differently depending on context, but here it will simply convert everything into a string and then "add" them together like letters or words. Now it becomes something like:
print('5' + '+' + '3' + '=' + '8')
Notice how each number is now a string by the surrounding quotes. This parses to:
print('5+3=8')
which prints the literal 5+3=8
You mean like that:
a = int(input("Give me a number man: "))
b = int(input("Give me another number: "))
print(f'print({a} + {b}) = {a + b}')
print(f'print({a} - {b}) = {a - b}')
print(f'print({a} * {b}) = {a * b}')
print(f'print({a} // {b}) = {a // b}')
print("Look at all those maths!")
Output
Give me a number man: 3
Give me another number: 2
print(3 + 2) = 5
print(3 - 2) = 1
print(3 * 2) = 6
print(3 // 2) = 1
Look at all those maths!

Sum of Digits in a specific way in Python

I'm looking for a code that runs, i.e:
int(input) = 2565
Printed Output should be like:
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
I wrote the code that gives final answer "9". But I couldn't managed to write it with every digit separated "+" sign. Assuming that I need to use while loop but how can I write the code so it will be like the output above?
You can use something like this:
def sum_of_digits(s):
if s < 10:
return s
return sum_of_digits(sum(int(c) for c in str(s)))
> sum_of_digits(2565)
9
It recursively checks if the numerical value is less than 10. If it does, it returns this value. If not, it adds the digits, then recursively calls itself on the result.
Edit
To print out the steps as it goes along, you could do something like this:
def sum_of_digits(s):
if s < 10:
print(s)
return s
print(' + '.join(c for c in str(s)) + ' = ')
return sum_of_digits(sum(int(c) for c in str(s)))
First, initiate an empty string output_str.
With a while loop which contniues when our integer is > 9:
[s for s in str(x)] would create a list of the digits (as strings) of our integer. It's called a list comprehension, is very useful, and my advice is to read a bit about it.
With " + ".join() we create a string with " + " between the
digits. Add this string at the end of output_str.
Add " = " to the end of output_str.
Calculate the sum of the digits (we cannot use sum(lst_of_digits) because it's a list of strings. sum([int(s) for s in lst_of_digits]) converts the string list into an inter list, which can be summed using sum()). Store the sum into x.
Add the new x + " = " to output_string.
At the end of the string, we have a redundant " = " (because the last (5) was not needed), let's just remove the last 3 chars (=) from it.
x = 2565
output_str = ""
while x > 9:
lst_of_digits = [s for s in str(x)]
output_str += " + ".join(lst_of_digits)
output_str += " = "
x = sum([int(s) for s in lst_of_digits])
output_str += f"{x} = "
output_str = output_str[:-3]
outputs:
output_str = '2 + 5 + 6 + 5 = 18 = 1 + 8 = 9'
You can play around with the end keyword argument of the print function which is the last character/string that print will put after all of its arguments are, well, printed, by default is "\n" but it can be change to your desire.
And the .join method from string which put the given string between the given list/iterable of strings to get the desire result:
>>> " + ".join("123")
'1 + 2 + 3'
>>>
Mixing it all together:
def sum_digit(n):
s = sum(map(int,str(n)))
print(" + ".join(str(n)),"=",s, end="")
if s<10:
print()
return s
else:
print(" = ",end="")
return sum_digit(s)
Here we first get the sum of the digit on s, and print it as desire, with end="" print will not go to the next line which is necessary for the recursive step, then we check if done, and in that case print a new empty line if not we print an additional = to tie it for the next recursive step
>>> sum_digit(2565)
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
9
>>>
This can be easily be modify to just return the accumulated string by adding an extra argument or to be iterative but I leave those as exercise for the reader :)
I am a noob but this should do what you want.
Cheers,
Guglielmo
import math
import sys
def sumdigits(number):
digits = []
for i in range( int(math.log10(number)) + 1):
digits.append(int(number%10))
number = number/10
digits.reverse()
string = ''
thesum = 0
for i,x in enumerate(digits):
string += str(x)
thesum += x
if i != len(digits)-1: string += ' + '
else: string += ' = '
if thesum > 10:
return string,thesum,int(math.log10(number))+1
else:
return string,thesum,0
def main():
number = float(sys.argv[1])
finalstring = ''
string,thesum,order = sumdigits(number)
finalstring += string
finalstring += str(thesum)
while order > 0:
finalstring += ' = '
string,thesum,order = sumdigits(thesum)
finalstring += string
finalstring += str(thesum)
print 'myinput = ',int(number)
print 'Output = ',finalstring
if __name__ == "__main__":
main()

How to change the following output into a proper string?

I'm trying to code a chatbot that will print a string containing n times the first letter of my name, followed by "n" and then followed by n-1 times the second letter in my name.
Example:
name: chris
n = 5 (since there are 5 letters in the name)
n-1 = 4
first letter of the name: c
second letter of the name: h
The string I want to generate: ccccc5hhhh
My problem: The string generated is in brackets which I don't want. I want the string to be exactly as "ccccc5hhhh", no spaces; all in one line, but I keep getting ['c','c','c','c','c']5['h','h','h','h'] as the output.
st1 = input("First name? ==> ")
print("Please enter the first letter of your name")
letter = input ("First letter? ==>? ")
if (letter == st1[0]):
# initializing list of lists
test_list = st1[0]
test_list1 = st1[1]
# repeat letters n times
res = [ele for ele in test_list for i in range(len(st1))]
res2 = [ele for ele in test_list1 for i in range(len(st1)-1)]
# printing result
print(str(res), len(st1), str(res2))
You are looking for the join function. Using , with your arguments will insert a space though.
To get the result you are looking for you will want:
print(''.join(res) + str(len(st1)) + ''.join(res2))
Instead of converting your lists into string you can use the .join() function, like so ''.join(res)
So you final line should be:
print(''.join(res) + str(len(st1)) + ''.join(res2))
You're overcomplicating this. Just use string multiplication.
s = 'chris'
n = len(s)
res1 = s[0] * n
res2 = s[1] * (n - 1)
print(res1 + str(n) + res2) # -> ccccc5hhhh

How to repeat string message without use asterisk, loop, array, import

I get a quiz about programming python.
Input: 3 lines of any string. (only 3 lines)
Output: 3 * 5 = 15 lines of string which repeat 3 lines of input 5 rounds
** But this quiz has restricted word: import for while * . sep if else elif list set tuple dict [] {} lambda map filter
I already try it by use asterisk character to repeat string but this is restricted word. It cannot submit.
STRING_A = input()
STRING_B = input()
STRING_C = input()
STRING_RESULT = STRING_A + "\n" + STRING_B + "\n" + STRING_C + "\n"
print(STRING_RESULT * 5)
Example
Input:
man
in
middle
Output:
man
in
middle
man
in
middle
man
in
middle
man
in
middle
man
in
middle
Thanks for your helping.
Given your restrictions, recursion sounds like a good approach. Give this a shot!
def repeater(a,n):
n <= 0 and exit(0)
n == 1 and print(a)
print(a)
return(repeater(a,n-1))
STRING_A = input()
STRING_B = input()
STRING_C = input()
STRING_RESULT = STRING_A + "\n" + STRING_B + "\n" + STRING_C
repeater(STRING_RESULT, 5)
Output:
man
in
middle
man
in
middle
man
in
middle
man
in
middle
man
in
middle

How to search & replace in Python?

How can I add a character "-" to a string such as 'ABC-D1234', so it becomes 'ABC-D-1234'?
Also, how can I add a character after the first 2 number, ie from 'ABC-D1234' to 'ABC-D12-34' Many thanks.
It depends on the rule you are using to decide where to insert the extra character.
If you want it between the 5th and 6th characters you could try this:
s = s[:5] + '-' + s[5:]
If you want it after the first hyphen and then one more character:
i = s.index('-') + 2
s = s[:i] + '-' + s[i:]
If you want it just before the first digit:
import re
i = re.search('\d', s).start()
s = s[:i] + '-' + s[i:]
Can I add a character after the first 2 number, ie from 'ABC-D1234' to 'ABC-D12-34'
Sure:
i = re.search('(?<=\d\d)', s).start()
s = s[:i] + '-' + s[i:]
or:
s = re.sub('(?<=\d\d)', '-', s, 1)
or:
s = re.sub('(\d\d)', r'\1-', s, 1)
You could use slicing:
s = 'ABC-D1234'
s = s[0:5] + '-' + s[5:]
Just for this string?
>>> 'ABC-D1234'.replace('D1', 'D-1')
'ABC-D-1234'
If you're specifically looking for the letter D and the next character 1 (the other answers take care of the general case), you could replace it with D-1:
s = 'ABC-D1234'.replace('D1', 'D-1')

Categories