how can I convert string to list in python [duplicate] - python

This question already has answers here:
How do I split a string into a list of words?
(9 answers)
Closed 6 years ago.
i am trying to parse a xml file, it works very well. I have string output, which i would like to make as list, but i doesnot work.
I get for tuple or list, that every line is a list...Somebody any idea?
def handleToc(self,elements):
for element in elements:
self.name = element.getElementsByTagName("name")[0]
self.familyname = element.getElementsByTagName("family")[0]
#self.position = element.getElementsByTagName("position")[0].firstChild.nodeValue
position = element.getElementsByTagName("position")[0].firstChild.nodeValue
liste=position.encode('utf-8')
nameslist = [y for y in (x.strip() for x in liste.splitlines()) if y]
#print names_list[1:-1]
#print ''.join(repr(x).lstrip('u')[1:-1] for x in position)
#converted_degrees = {int(value) for value in position}
liste1=tuple(liste)
print liste
print list1
and the output is:
66.5499972
70.5500028
73.7
76.3
79.4499972
83.4500028
86.6
89.2

replace
listel= tuple(liste)
with
liste1 = liste.split(' ')
split(' ') will split the string into a list of items, and access it with index
say listel[0] for first item. liste1[1] for second item and so on.

Related

Why can't I manipulate inputted list (list = [input()]) ? If possible, how? [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 1 year ago.
I am creating a sequence identifier and I want a shorter code by manipulating the list. However:
#This is possible:
list = [1,2,3,4,5]
A = list[1] - list[0]
print(A)
#This is not possible:
list = [input()]
A = list[1] - list[0]
print(A)
[input()] is only one (string) element, so list[1] doesn't exist to be used in subtraction.
If you want a list of 5 user-entered integers, you would use
[int(input()) for _ in range(5)]
And press enter after each value
Or for space-separated values - [int(x) for x in input().split()]

How to replace variable in string in a list [duplicate]

This question already has answers here:
Changing one character in a string
(15 answers)
Closed 2 years ago.
I have a list called x below and I want to replace the ">" (in x[0][0]) with the integer 1.
x = [">000#","#0#00","00#0#"]
I tried x[0][0] = 1 but it gives me an error.
Also, can I make x[0][2] to become an integer such that
x[0][2] += 1 becomes this:
x = ["1010#","#0#00","00#0#"]
You can try
x[0]=x[0].replace(">","1")
Strings are immutable so cant be changed like list.
Or you can convert to list.
x[0]=list(x[0])
x[0][0]="1"
x[0][2]=str(int(x[0][2])+1)
x[0]="".join(x[0])
Python strings are immutable; you cannot change their contents. Instead, you need to make a new string out of the old one and assign that to x[0]:
x = [">000#","#0#00","00#0#"]
# change the first character to a '1'
x[0] = '1' + x[0][1:]
# add 1 to the third character
x[0] = x[0][:2] + str(int(x[0][2]) + 1) + x[0][3:]
print(x)
Output:
['1010#', '#0#00', '00#0#']

How do you replace a '|' with ' ' or null string? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
I removed all the null values and numbers from my data. I only have list of lists containing text strings and '|'. I want to loop over my RDD object and replace the '|' with '' or even remove it.
I tried using the map function and then I linked it to an external function
def fun(item):
newlist=list()
for i in item:
if '|' == i or '|' in i:
j=''
newlist.append(j)
else:
newlist.append(i)
return newlist
final=orginial.map(x : fun(x))
input: [['Hello','|'],..]
expected output: [['Hello',''],..]
actual output: [['Hello','|'],..]
you can use replace in python.
a = "ABCD|EFG"
a = a.replace("|", "")
i change the code you can use this:
def fun(item):
newlist=list()
for i in item:
newlist.append(i.replace("|",""))
return newlist
if you want to get rid of the empty strings you could also try this
output = []
for single_list in list_of_lists:
new_in_list = [i for i in single_list if not i is "|"]
output.append(new_in_list)
i add more example :
a = ["hello|||", "he||oagain", "|this is |", "how many ||||||||| ?"]
output = []
for i in a:
output.append(i.replace("|", ""))
print(output)
at the end output is :
['hello', 'heoagain', 'this is ', 'how many ?']

retrieve in list occurrences from text python [duplicate]

This question already has answers here:
Modifying list while iterating [duplicate]
(7 answers)
Closed 5 years ago.
Text = input('please enter your text')
l = [str(x) for x in Text.split()]
count = 0
for item in l:
for i in range(1,len(item)):
if item[i-1] == item[i]:
count +=1
if count <1:
l.remove(item)
count = 0
print (l)
the goal is : if we have a text : 'baaaaah mooh lpo mpoo' to get a list with elements they have 2 successive same characters, in this case ['baaaaah', 'mooh', 'mpoo' ]
the program is working with the mentioned example
if i use this one it's not working : 'hgj kio mpoo'
thank you
(complex)One liner:
>>> def successive_items(s):
return [x for x in s.split() if any(x[i]==x[i-1] for i in range(1,len(x)))]
>>> successive_items('baaaaah mooh lpo mpoo')
['baaaaah', 'mooh', 'mpoo']
>>> successive_items('hgj kio mpoo')
['mpoo']
In case of your code, you should not modify the list you are iterating over. Say, for example, lets have an array:
a = [1,2,3,4,5]
Now, if you iterate and remove elements (inside the loop), you would expect a to be empty. But let's check out:
>>> a = [1,2,3,4,5]
>>> for item in a:
a.remove(item)
>>> a
[2, 4]
See? It is not empty. This is better explained here.
Your program is not working for the second case because of list modification. Here is how:
Initially your list had ['hgj','kio','mpoo'].
After reading the first element you removed hgj. So the list now becomes ['kio','mpoo'].
The loop iterates the 2nd element next, and it gets mpoo (in the modified list);
kio was never read.
This might help:
sentence = input("please enter your text")
words = sentence.split()
answers = []
for each_word in words:
for idx in range(1, len(each_word)):
if each_word[idx] == each_word[idx-1]:
answers.append(each_word)
break
print(answers)
In your code, you are iterating over a list and at the same time you are modifying that very same list(by deleting elements from it), for more explanation see this answer

How to return a string from an array [duplicate]

This question already has answers here:
How can I convert each item in the list to string, for the purpose of joining them? [duplicate]
(9 answers)
Closed 7 years ago.
keyword = raw_input ("Enter your keyword") *10000
keyword = keyword.lower()
keywordoutput = []
for character in keyword:
number = ord(character)
keywordoutput.append(number)
input1 = raw_input('Write Text: ')
input1 = input1.lower()
output1 = []
for character in input1:
number = ord(character)
output1.append(number)
output2 = [x + y for x, y in zip(output1, keywordoutput)]
print output2
That is my code so far. I am trying to create a program that uses a simple Vigenere Cypher to encrypt an inputted text. The code works perfectly, yet I am having an issue implimenting new code to return a string of 'output2'.
I get 'output2' easily, but from there i need to make it a simple string.
Eg: [1, 2, 3, 4]
becomes (1234)
I have tried, but I cant seem to implement such a thing into my code.
First you have to convert numbers into text.
output2 = map(str, output2)
Then you can use join to concatenate elements.
print "".join(output2)
Or in one line:
print "".join(map(str, output2))
try this
print ''.join(str(i) for i in output2)
One step use -> join:
output2 = ''.join([str(x + y) for x, y in zip(output1, keywordoutput)])
Check: https://docs.python.org/2/library/string.html#string.join
As the function is expecting a string type you must covert the numeric result x + y.

Categories

Resources