j=0
while j<5:
random_lines=random.choice(men_heroes_lines)
element=(random_lines.split(":")[0:1])
random_lines_women=random.choice(women_heroes_lines)
element_women=(random_lines_women.strip("\n").split(":")[0:1])
print element
print element_women
j=j+1
hey guys here is my question.. i have two txt files which contains men and women names..
as:
manname1: a b c d
manname2: x y z e
...
i managed stripping to ":" but i can't write them side by side in a list..
expected output is=
["manname1","manname2","manname3"...]
however it is:
["manname1"]
["manname2"]
["manname3"]
how can i do it as in the expected output.. thanx in advance :)
this is my sample file..
Ant Man: a, b
Frodo: x,y
Star : s, d
Thor: r, t
Spy: p,u
ant man,frodo,star... is the men mame.. and what i want to append a list..
Maybe create another list for example names and instead of printing the element on each iteration append it to this list. And then print the list after the loop is over.
j=0
women_names = []
while j < 5:
. . .
women_names.append(element_women)
j += 1
print women_names
As a general approach, instead of print use
import sys
sys.stdout.write(element)
sys.stdout.write(element_women)
which does not add newlines at the end.
In Python 3 note
print(element, end="")
print(element_women, end="")
In case the input does not show immediately (large buffer), consider respectively
sys.stdout.flush()
and
print(element, end="", flush=True)
try to use ','
print element,
print element_women
example:
print 'a',
print 'b'
output
a b
Related
The question for the code is 'input a word and check whether the first character of the word is repeated in the word again or not. If yes then change all the repeating characters to $ except the first character.'
So I coded the following and used the logic to start the loop from the second character of the word so that first character remains unchanged.
a=input()
for i in range(1,len(a)):
if(a[i]==a[0]):
b=a.replace(a[i],'$')
print(b)
for the above program I gave the input as 'agra' and to my surprise got the output as '$gr$'. the first character was also changed.
What is the problem with my logic? and what other solution do you suggest?
That is more simply done like:
Code:
b = a[0] + a[1:].replace(a[0], '$')
Test Code:
a = 'stops'
b = a[0] + a[1:].replace(a[0], '$')
print(b)
Results:
stop$
For the correct solution in python, see Stephen Rauch's answer.
I think that what you where trying to achieve, in a very "unpythonic" way, is:
a = input()
b = a # b is a copy
for i in range(1, len(a)):
if a[i] == a[0]:
# replace i-th char of b by '$''
print (b)
How to do that replacement? In python: strings are immutable, that means you cannot replace a char "in place". Try to do this:
a='agra'
a[3] = '$'
And you'll get an error:
TypeError: 'str' object does not support item assignment
If you want to replace the i-th char of a string by $, you have to write:
b = b[:i] + '$' + b[i+1:]
That is: build a new string from b[0], ..., b[i-1], add a $ and continue with b[i+1], ..., b[len(a)-1]. If you use this in your code, you get:
a = input()
b = a
for i in range(1, len(a)):
if a[i] == a[0]:
b = b[:i] + '$' + b[i+1:]
print (b)
Okay, it works but don't do that because it's very "unpythonic" and inefficient.
BEGIN EDIT
By the way, you don't need to replace, you can just build the string character by character:
a = input()
b = a[0] # start with first char
for i in range(1, len(a)):
if a[i] == a[0]:
b += '$' # $ if equals to first char
else:
b += a[i] # else the current char
print (b)
END EDIT
That gave me this idea:
a=input()
b="".join('$' if i!=0 and c==a[0] else c for i,c in enumerate(a))
print(b)
Explanation: the list comprehension takes all characters of a along with their position i (that's what enumerate does). For every couple position, character, if the position is not 0 (not the first character) and if the character is equal to a[0], then put a $. Else put the character itself. Glue everything together to make a new string.
Again, that's not the right way to do what you are trying to do, because there is another way that is neater and easier (see Stephen Rauch's answer), but is shows how you can sometimes handle difficulties in python.
a=input()
for i in range(1,len(a)):
if(a[i]==a[0]):
b=a[1:len(a)].replace(a[i],'$')
print(a[0]+b)
you changed whole word/sentence 'a': a.replace(...)
I am new to Python 3 and programming in general. I am not sure how to word my question so I'll just give an example.
So the user inputs a string such as "home". The program should output:
h
ho
hom
home
This is what I have so far (I was just trying to get the numbering to work, but I thought I would add it just in case):
loopUpdate = 2
for i in range(1, len(mystery_string) + 1):
for x in range(1, loopUpdate):
print(x, end="")
loopUpdate += 1
print()
This is unnecessarily complicated. You don't have to have two loops to print out characters at each index in a loop. You should use string slicing instead:
>>> "home"[0:2]
'ho'
>>> "home"[0:3]
'hom'
A function that does this would look something like this:
def print_loop(word):
for i in range(1, len(word) + 1):
print(word[0:i])
Output:
>>> print_loop("word")
w
wo
wor
word
I am trying to print out a decimal integer(non-negative) as sum of powers of 2 i.e for input 10, it should print "2 8" without quotes. I already wrote this code, but can someone give me a one liner for this.
n = bin(int(raw_input()))[-1:1:-1]
print (' ').join([str((int(n[j])+1)**j) for j in xrange(len(n)) if n[j] == '1'])
It much better to have this spread across muplitple lines, and using and input inside a list comprehension hides a key piece of the information of what your code is doing.
Ultimately, what you are asking to doisn't pretty, but here it is anyway:
print (' ').join([str(2**i) for i,j in enumerate(bin(int(raw_input()))[-1:1:-1]) if j == '1'])
Pretty printed it is:
print ' '.join(
[str(2**i)
for i,j in enumerate(
bin(int(raw_input()))[-1:1:-1]
)
if j == '1']
)
Notes:
int(n[j])+1) will always be 2, since you are only iterating if j is 1.
enumerate returns a list of tuples each containing the index and value, so you don't need to store n, and can test against j directly.
Python can iterate over a list of items without having to fetch them by index, its the difference between [list[i]**2 for i in len(list)] and [i**2 for i in list]
You don't need to put brackets around the string, so you can save some space by doing this:
" ".join(...)
Instead of this:
(" ").join(...)
I want to make multiple lists with my for loops, My code is:
for port in portlist1:
print port.getname(),port.getsize()
for register in port.getregisters():
j=j+1
print j
j=0
Output is:
B 10
1
C 15
1
F 30
1
I want to make list every time:
List1=[[B,10],1]
List2=[[C,15],1]
List3=[[F,30],1]
Can someone help me here?
lists = []
for port in portlist1:
l = [[port.getname(), port.getsize()]]
for register in port.getregisters():
j=j+1
l.append(j)
lists.append(l)
j=0
It's not clear what was the value of j before the loop, but it looks like you are using it to measure the length of port.getregisters(). Try this one-liner:
result = [[[port.getname(), port.getsize()], len(port.getregisters())] for port in portlist1]
It's a bad idea to make a new list each time, you should just go with nesting each list. If the amount of ports is static, you can use vars()['listX'].. But still not really recomended. You should go with the answer given by kroolik or alecxe
But if you REALLY need someting like..:
List1=[[B,10],1]
List2=[[C,15],1]
List3=[[F,30],1]
You can use:
lname = "list"
for i,p in enumerate(portlist1):
j = len(p.getregisters())
vars()[lname+str(i)] = [(p.getname(),p.getsize()), j]
print list0
print list1
print list2
Is there any simple way to find the Last Iteration of the for Loop in Python? I just want to convert a list to CSV.
To convert a list to CSV, use the join-function:
>>> lst = [1,2,3,4]
>>> ",".join(str(item) for item in lst)
"1,2,3,4"
If the list already contains only string, you just do ",".join(l).
Your best solution is probably to use the csv module, as suggested elsewhere. However, to answer your question as stated:
Option 1: count your way through using enumerate()
for i, value in enumerate(my_list):
print value,
if i < len(my_list)-1:
print ", followed by"
Option 2: handle the final value (my_list[-1]) outside the loop
for value in my_list[:-1]:
print value, ", followed by"
print my_list[-1]
To convert a list to csv you could use csv module:
import csv
list_of_lists = ["nf", [1,2]]
with open('file', 'wb') as f:
csv.writer(f).writerows(list_of_lists)
The 'file' file would be:
n,f
1,2
actually when a for loop in python ends the name that it bound is still accessible and bound to its last value:
for i in range(10):
if i == 3:
break
print i # prints 3
i use this trick with with like:
with Timer() as T:
pass # do something
print T.format() # prints 0.34 seconds
Not exactly what you want:
>>> for i in range(5):
print(i)
else:
print("Last i is",i)
0
1
2
3
4
Last i is 4
Edited: There is csv module in standard library, or simply ','.join(LIST)