Just use rstrip().
result = your_string.rstrip(',')
Answer from Amber on Stack Overflow for i in range(1, 21):
if i % 15 == 0:
print ('FizzBuzz',end=',')
elif i % 3 == 0:
print ('Fizz',end=',')
elif i % 5 == 0:
print ('Buzz',end=',')
else:
print (i,end=',')Output is 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz,16,17,Fizz,19,Buzz,
I would use ",".join() with a generator expression to do this.
But with your setup you can simply have an if statement to see if you are on your final value for i (20 in this case) and opt to not print your comma then.
You could do something really abusive also, like multiplying the "," by i-19 to concat the comma using string multiplication (i.e. "a"*8 == "aaaaaaaa"). I think that "a"*(i-19) == "" for i =(1,19), and "a"*(i-19) == "a" for i = (20,39) (please don't do that though, haha). needs major refactoring i had a brainfart.
sorry for the bad indentation!
Hello guys, im a beginner in python and im having trouble with my tuple:
im trying to remove the last comma inside my print, now,i've managed this to kinda work, but now the code is repeating itself due to a for that i have:
Heres the code:
my_tuple = (int(input('type a value: ')),
int(input('Digite outro valor: ')),
int(input('Digite mais um valor: ')),
int(input('type another value: ')))
print('even: ')
for c in my_tuple:
if c % 2 == 0:
print(*my_tuple, sep=', ')The output:
type a value: 4 type another value: 8 type another value: 10 type another value: 2 4, 8, 10, 2 4, 8, 10, 2 4, 8, 10, 2 4, 8, 10, 2
The output i want:
type a value: 4 type another value: 8 type another value: 10 type another value: 2 4, 8, 10, 2
i know this is due to the "for" but i do not know how to do it any other way since i cannot do if my_tuple % 2 == 0
You could build a list of strings in your for loop and print afterword using join:
strings = []
for ...:
# some work to generate string
strings.append(sting)
print(', '.join(strings))
alternatively, if your something has a well-defined length (i.e you can len(something)), you can select the string terminator differently in the end case:
for i, x in enumerate(something):
#some operation to generate string
if i < len(something) - 1:
print(string, end=', ')
else:
print(string)
UPDATE based on real example code:
Taking this piece of your code:
value = input("")
string = ""
for unit_value in value.split(", "):
if unit_value.split(' ', 1)[0] == "negative":
neg_value = unit_value.split(' ', 1)[1]
string = "-" + str(challenge1(neg_value.lower()))
else:
string = str(challenge1(unit_value.lower()))
print(string, end=", ")
and following the first suggestion above, I get:
value = input("")
string = ""
strings = []
for unit_value in value.split(", "):
if unit_value.split(' ', 1)[0] == "negative":
neg_value = unit_value.split(' ', 1)[1]
string = "-" + str(challenge1(neg_value.lower()))
else:
string = str(challenge1(unit_value.lower()))
strings.append(string)
print(', '.join(strings))
If you can first construct a list of strings, you can then use sequence unpacking within print and use sep instead of end:
strings = ['5', '66', '777']
print(*strings, sep=', ')
5, 66, 777
If you want to do it your way:
for i in range(1, 21):
print(i, end="," if i!=20 else "" )
Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
But a better way of doing this would be:
print(*range(1, 21), sep=",")
This would be the most convenient way to do it in Python. Given any list, it will join the list together with whatever character you give it. This only works with list of strings so we have to convert the lsit of interegers to strings using map(str, your_list).
your_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
converted_list_to_string = map(str, your_list)
print(",".join(your_list))
If you want a space after the comma, simply add it to the ", ":
print(", ".join(your_list))
In the below code, the user inputs any number of entries into a tkinter text widget, in the format:
/[number], i.e. /20.
In my code I add a comma to the end of each user entry when the user prints it out. However, I need to remove the last comma from the list.
I've tried .replace(",", ""[-1]), but it still removes all of the commas. I've also tried re.sub but it does the same (though I haven't fully explored all of the options of re.sub, so there could be something that works).
Could I get some guidance here to remove only the last comma from any number of entries? Code is below with output.
txt1 = tk.Text(root, wrap = "none", width = 20, height = 10, undo = "True",)
txt1.grid(row = "0", column = "0")
def prefix_set():
target = txt1.get("1.0", 'end-1c')
result = re.findall("/\d+", target)
for i in result:
if (i.rpartition("/")[2]) <= str(23):
print(i + " le 24,")
else:
print(i + ",")
Entries in target:
/22
/23
/24
/24
Current output:
/22,
/23,
/24,
/25,
Desired output:
/22,
/23,
/24,
/25Notice that in any case: the if or else, first of all you print n. So you can always start by printing it. Now we can switch the comma to the start of the printing:
n = 15
k = 5
def pattern(n):
# Write your recursive function here
print(n, end='')
if n > 0:
print(', ', end='')
pattern(n-k)
print(', ' + str(n), end='')
pattern(n)
Gives:
15, 10, 5, 0, 5, 10, 15
Of course Tomerikoos answer does exactly what was requested. Here's a solution with a few other benefits:
n = 15; k = 5
def pattern(n):
if n < 0:
return [n]
else:
return [n] + pattern(n-k) + [n]
print(', '.join(map(str,pattern(n))))
Explanation:
- You calculate the items of the sequence, and store them in a list
- Printing is done afterwards:
- First, the function
stris mapped over the sequence, generating a sequence of strings. - Then, the sequerce is joined together using
str.joinon the comma.
- First, the function
Benefits:
- Separates print and computation code, which lets you do something else entirely with the sequence, once calculated
- Uses str.join, which is one of the most handy functions for displaying stuff
- Uses just one print statement.
A side note; you could use pythons inline if:
def pattern(n):
return [n] if n<0 else [n] + pattern(n-k) + [n]
You can use the sep parameter of print
numbers=[numbex(x) for x in range(1,11)]
print(*numbers, sep=",")
A nice pythonic way to do is by using join:
print(','.join([str(numbex(num)) for num in range(1,11)]))
The following term: [str(numbex(num)) for num in range(1,11)] will create a list, of strings, each string the output of your numbex function on a number from range(1,11).
','.join(...) will join them to a single string, separating each value by ,.
You want to replace it, not strip it:
s = s.replace(',', '')
Use replace method of strings not strip:
s = s.replace(',','')
An example:
>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True
You could use the join method:
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print("[", end="")
join_list = []
for i in range(0, x + 1):
for j in range(0, y + 1):
for k in range(0, z + 1):
if (i + j + k) != n:
join_list.append(f"[{i},{j},{k}]")
print(",".join(join_list), end="")
print("]", end="")
Or in combination with comprehesions:
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print(
"["
+ ",".join(
f"[{i},{j},{k}]"
for i in range(x + 1) for j in range(y + 1) for k in range(z + 1)
if i + j + k != n
)
+ "]",
end=""
)
Or use itertools.product instead of the nested comprehensions:
from itertools import product
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print(
"["
+ ",".join(
"[{},{},{}]".format(*p)
for p in product(range(x + 1), range(y + 1), range(z + 1))
if sum(p) != n
)
+ "]",
end=""
)
Or build the list first, then convert it to string and replace the blanks:
from itertools import product
x = int(input())
y = int(input())
z = int(input())
n = int(input())
result = [
list(p)
for p in product(range(x + 1), range(y + 1), range(z + 1))
if sum(p) != n
]
print(str(result).replace(" ", ""), end="")
append func is used to collect
y = int(input())
z = int(input())
n = int(input())
a = []
# print("[",end="")
for i in range(0,x+1):
for j in range(0,y+1):
for k in range(0,z+1):
if((i+j+k)!=n):
a.append([i,j,k])
print(a)
This is not too good in terms of performance if your string is very long, but it should do
"\n".join(x[:-1] for x in output.splitlines())
You can probably combine multiple rstrips if you have mixed endings, but the best answer is to use regular expressions.
import re
output = "1,2,3,4 \t\n"
print(re.sub(",\s*$", "", output))
outputs
1,2,3,4
I have a class called Count:
class Count:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
distance = float(math.sqrt((self.x - other.x) ** 2 + (self.y - other.y)**2))
return('%.2f,' % distance)
numbers = input()
n = [int(i) for i in numbers.split()]
def distance(n):
P1 = Count(n[0], n[1])
for x, y in zip(n[2:2]), n[3:2]):
P2 = Count(int(x), int(y))
print(str(P1.distance(P2)), end=' ')When I run it I get an output of the differences between the first point and all the others.
Ex: 2.34, 2.43, 4.30,
But I don't know how to get rid of the last comma, the one right after 4.30. I need a comma after everything except the last number.
Rather than printing each returned answer as you get it, you should add the answer to a list. Then you can print the entire list with join:
def distance(n):
P1 = Count(n[0], n[1])
results = []
for x, y in zip(n[2::2], n[3::2]):
P2 = Count(int(x), int(y))
results.append(str(P1.distance(P2)))
print(", ".join(results))
You'll have to remove the comma from the returned string on line 8. Also note I fixed your error on line 15.
Thank you. I'll look into that, it should help me out a lot.