my output from a forloop is
string = ""
for x in something:
#some operation
string = x += string
print(string)
5
66
777
I use the below code to have them on the same line
print(string, end=", ")
and then I get
5, 66, 777,
I want the final result to be
5, 66, 777
How do I change the code print(string, end=", ") so that there is no , at the end
The above string is user input generated it can me just 1 or 2,3, 45, 98798, 45 etc
So far I have tried
print(string[:-1], end=", ") #result = , 6, 77,
print((string, end=", ")[:-1]) #SyntaxError: invalid syntax
print((string, end=", ").replace(", $", "")) #SyntaxError: invalid syntax
print(", ".join([str(x) for x in string])) # way off result 5
6, 6
7, 7, 7
print(string, end=", "[:-1]) #result 5,66,777,(I thought this will work but no change to result)
print(*string, sep=', ') #result 5
6, 6
7, 7, 7
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
user input
twenty five, four, nine
gets
25, 4, 9, #(that stupid comma in the end)
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
In case your for loop is doing also something else than printing, then you can maintain your current structure with this approach.
strings = ['5', '66', '777']
for i in range(len(strings)-1):
# some operation
print(strings[i], end=', ')
# some operation (last time)
print(strings[-1])
5, 66, 777
see I have solved this to print 1 to 5
Previously:
i = 1
while i<=5:
print(i, end=",")
i=i+1
Output:==> 1,2,3,4,5,
Now
lst=[]
i=1
while i<=5:
lst.append(str(i))
i=i+1
print(', '.join(lst))
Output:==> 1,2,3,4,5
I can suggest you to use a if-condition inside a for-loop like below
x=['1','2','3','4','5'] #Driver List
for i in range(0,len(x),1): #This loop iterates through the driver list
if( i==len(x)-1 ): #This checks whether i reached the last positon in iteration
print(i) #If i is in the last position, just print the value of i
else:
print(i,end=" , ") #If i is not in the last position, print the value of i followed by a comma
The output for this code is:
0 , 1 , 2 , 3 , 4 #Notice that no comma is printed in the last position
If text formatting is a concern, the simplest approach is to remove the last comma as shown in this example:
letters = ["a", "b", "c", "d", "e", "f"]
for i in letters:
print(f"{i}".upper(), end=", ") # some text formatting applied
print("\b\b ") # This removes the last comma.
Otherwise,
print (*letters, sep=", ")
works pretty well.
for i in range(10):
if(i==9):
print(i)
else:
print(str(i),end=",")
output : 0,1,2,3,4,5,6,7,8,9
list_name = [5, 10, 15, 20]
new_list = []
[new_list.append(f'({i}*{i+5})') for i in list_name]
print(*new_list,sep="+")
Output: (5*10)+(10*15)+(15*20)+(20*25)
for i in range(1,10):
print(i, end="+")
print("10")
Output:
1+2+3+4+5+6+7+8+9+10
in the end no + sign.
Related
So im trying to get first letters of words(excluding first word, i already solved that) in a sentence.
But it appends spaces to the list.
Would appreciate if you help.
Here's the code:
lst = []
for t in (input()):
if t == " ":
lst.append(t)
print(*lst, sep="")
input1: asd dfd yjs
output1: dy
just this:
''.join([s[0] for s in input().split()[1:]])
step by step:
if input() returns asd dfd yjs
split string (more):
input().split() # output: ['asd', 'dfd', 'yjs']
sub list (more):
input().split()[1:] # output: ['dfd', 'yjs']
one line loop (more):
[s[0] for s in ['dfd', 'yjs']] # output: ['d', 'y']
sub string (more):
s="dfd"
s[0] # output: d
concat list of strings (more):
''.join(['d', 'y']) # output: dy
You're getting spaces because that's what you asked for. Read your code out loud and it will probably make sense:
if t == " ":
lst.append(t)
If t is a space, append it to lst
Seems clear that you will only get spaces.
You want the character after t to be appended. There's two ways to do that using your for loop method: 1) if t is a space, append the next character; 2) if the previous character was a space, append t. Here's how you might implement #2:
lst = []
prev_char = None
for t in (input()):
if prev_char == " ":
lst.append(t)
prev_char = t
print(*lst, sep="")
This will print the first character of ever word except the first word. Initialize last_char to a space to include the first word.
You may
split your sentence into words using x.split()
remove the first word, using a slice [1:] (from index 1 to the end)
then keep only the first char of each word and concatenate it to a result string
x = input(">")
result = ""
for word in x.split()[1:]:
result += word[0]
print(result) # dy
Using a generator and str.join :
x = input(">")
result = ''.join(word[0] for word in x.split()[1:])
You could use str.split:
lst = [s[0] for s in input().split()[1:]]
A simple example:
lst = []
get_next = False
for t in input():
if t == " ":
get_next = True
elif get_next:
lst.append(t)
get_next = False
print(*lst, sep="")
A lot great answers already and this is good case for split. If you specifically need to collect the next token after a special token in a stream of tokens, here are some other options:
inp = "asd dfd yjs"
lst = []
for a, b in zip(inp[:-1],inp[1:]):
if a == " ":
lst.append(b)
print(*lst, sep="")
# With comprehensions - my choice
print("".join([b for a, b in zip(inp[:-1],inp[1:]) if a == " "]))
# With functional approach
from functools import reduce
from operator import add, itemgetter
def has_prior_space(x):
return x[0] == " "
print(reduce(add, map(itemgetter(1), filter(has_prior_space, zip(inp[:-1], inp[1:])))))
In Python 3.10, there will be a new pairwise iterator that does this type of "2 at a time" iteration specifically: zip(inp[:-1],inp[1:])
Use Array join():
''.join(lst)
Usually, we input() a list in Python 3.X like this:
x = list(map(int, input()))
print (x)
But here let's say we give an input of 1234 then it prints:`
[1, 2, 3, 4]
Is there a way that I can print it like:
[12, 34]
Thanks in Advance!
Let's say you want the numbers to be entered separated by spaces. First get the entire line as input:
line = input()
Now parse the input. In this case, split on spaces:
words = line.split(' ')
Finally, convert each "word" to an int:
numbers = [int(i) for i in words]
Of course you can use map() instead of a list comprehension.
Note that this requires input such as
12 34
You can do this all in one line, but it is better to use variables to store each intermediate step. When you get it wrong, you can debug much more easily this way.
In my opinion, I would not complicate things :
I would declare an empty list :
l = []
Then I would simply append the input :
for i in range(0, n):
print("l[", i, "] : ")
p = int(input())
l.append(p)
You can notice here the "n",it's the size for the list,in your case it would be:
for i in range(0, 1):
print("l[", i, "] : ")
p = int(input())
l.append(p)
We always start from 0,so range(0,1) would count 0, then 1 and so on with other cases.
Hope this would help.
If I'm given:
point_loads, 3, 500
point_loads, 6, 900
point_loads, 12, 300
This code:
for line in open("Input.txt"):
li=line.strip()
if li.startswith("point_load"):
l = li.split(',')
for num in l[1:]:
num = float(num.strip())
point_loads.append(num)
prints:
point_loads = [3, 500, 6, 900, 12, 300]
I am trying to modify it so that if I'm given:
length = 32
point_loads, 3, 500
point_loads, 6, 900
point_loads, end, 300
It will set 'end' equal to 32 (or the variable length) so that the output is:
point_loads = [3, 500, 6, 900, 32, 300]
I tried a few different things, this was my latest...
for line in open("Input.txt"):
li=line.strip()
if li.startswith("point_load"):
l = li.split(',')
for num in l[1:]:
if num == 'end':
num = 10
num = float(num.strip())
point_loads.append(num)
but it gave me the error: (plus it wouldn't have really have done what I wanted, but it was a start)
num = float(num.strip())
ValueError: could not convert string to float: 'end'
When debugging, I can see that I need to strip the string so that it doesnt preform an operation on ' end'.
I've tried messing around with different bits of code for a few hours now, but have made no progress.
Any tips for this part?
Thank you!
I'm not sure. But it might what you want?
for line in open("Input.txt"):
li = line.strip()
if li.startswith("point_load"):
l = li.split(', ')
for num in l[1:]:
if num == 'end':
num = '10'
num = float(num.strip())
point_loads.append(num)
l = li.split(',') turns to l = li.split(', '), use both , and to split string to list
num = 10 turns to num = '10' make all elements are string to call strip()
If I understand your problem, you are unable to exchange the string 'end' with a variable of your choosing. Based on what you've said, it's because you are not matching strings correctly first. When you split the line by comma, you are still getting whitespace for each item.
'point_loads, end, 300'.split() ends up as `['point_loads', ' end', ' 300']
In order to fix this I would first filter your lines to strip all whitespace from each item after the split. Then when you test if num == 'end' you will get True. Your current code is testing if 'end' == ' end' which is False.
point_loads = []
with open(path, 'r') as f:
for line in f:
li = line.strip()
if li.startswith("point_load"):
l = li.split(',')
l = [x.strip() for x in l] # strip whitespace from each item
for num in l[1:]:
if num == 'end':
num = 10.
else:
num = float(num.strip())
point_loads.append(num)
I noticed the second part of your problem has to do with the nature of Python and duck typing. You are trying to call a string method strip() on ints and strings. In my above code if it matches your string it assigns an int otherwise it will convert the string to an int thus avoiding the issue of trying to call strip on an int.
EDIT I fixed the code - I had made a typo and used split() instead of strip() in the list comprehension. I tested this in python3.6 but it should also work in python2.7. I added a proper context manager for opening the file too which you should always do.
I am trying to make s programme that takes text and gives back to the user every 3rd letter including the first letter.This is what i wrote.
msg = input('Message? ')
for i in range(len(msg)):
(i) = (i*3)
print(msg[i], end=' ')
This gives back every thurd letter including the 1st letter but then also gives the error:
File "program.py", line 4, in
print(msg[i], end=' ')
IndexError: string index out of range
Also the software I am using says: Testing the first example but ignoring whitespace. Your submission raised an exception of type IndexError. This occurred on line 4 of your submission.
Whats the simplest way to fix this?
Let's say you have the string "Here we are". It has length 11. You are letting i go all the way to the end of the string, but once i reaches 4, that string at index i * 3 (12) is not defined. Instead, you shouldn't go farther than i divided by 3 (rounding down). This is how you would do that:
msg = input('Message? ')
for i in range((len(msg) // 3) + 1):
(i) = (i*3)
print(msg[i], end=' ')
what you want to do can easily be achieved by slicing the string
msg = input('Message? ')
print(msg[::3])
This should work:
msg = input("Message?: ")
count = 1
for i in msg:
if count % 3 == 0:
print("First char in string is " + msg[0] + ", the third is " + i)
count += 1
You can increment the range in steps of 3:
msg = input('Message? ')
for i in range(0, len(msg), 3):
print(msg[i], end=' ')
I'm currently doing a project for my university, and one of the assignments was to get python to only print the odd characters in a string, when I looked this up all I could find were string slicing solutions which I was told not to use to complete this task. I was also told to use a loop for this as well. Please help, thank you in advance.
Here is my code so far, it prints the string in each individual character using a for loop, and I need to modify it so that it prints the odd characters.
i = input("Please insert characters: ")
for character in i:
print(character)
Please follow this code to print odd numbered characters
#Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 != 0):
#print odd characters
print(i[index])
Another option:
a= 'this is my code'
count = 1
for each in list(a):
if count % 2 != 0:
print(each)
count+=1
else:
count+=1
I think more information would be helpful to answer this question. It is not clear to me whether the string only contains numbers. Anyway, maybe this answers your question.
string = '38566593'
for num in string:
if int(num) % 2 == 1:
print(num)
To extend on Kyrubas's answer, you could use-
string = '38566593'
for i, char in enumerate(string):
if i % 2 == 1:
print(char)
person = raw_input("Enter your name: ")
a = 1
print"hello " , person
print "total : " , len(person)
for each in list (person):
if a % 2 ==0:
print "even chars : " , (each)
a+=1
else:
a+=1
s = raw_input()
even_string=''
odd_string=''
for index in range(len(s)):
if index % 2 != 0:
odd_string = odd_string+s[index]
else:
even_string = even_string+ (s[index])
print even_string,odd_string
Try this code. For even index start you can use range(0, len(s), 2).
s = input()
res = ''
for i in range(1,len(s),2):
res +=s[i]
print(res)
When we want to split a string, we can use the syntax:
str[beg:end:jump]
When we put just one number, this number indicates the index.
When we put just two numbers, the first indicates the first character (included) and the second, the last character (excluded) of the substring
You can just read the string and print it like this:
i = input("Please insert characters: ")
print(i[::2])
When you put str[::] the return is all the string (from 0 to len(str)), the last number means the jump you want to take, that meaning that you will print the characters 0, 2, 4, etc
You can use gapped index calling. s[start:end:gap]
s = 'abcdefgh'
print(s[::2])
# 'aceg'
returning the characters with indexes 0, 2, 4, and 6. It starts from position 0 to the end and continues with a gap of 2.
print(s[1::2])
# 'bdfh'
Returning the characters with indexes 1, 3, 5, and 7. It starts from position 1 and goes with a gap of 2.