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 ?']
Related
This question already has answers here:
Understanding slicing
(38 answers)
Closed 2 years ago.
I have a list like this:
["*****", "*****"]
I want to insert the elements of another list to the middle of this list like this:
["*****", "abc", "ded", "*****"]
However, my attempt produces a list nested inside another list:
["*****", ["abc", "ded"], "*****"]
This is my code:
def addBorder(picture):
length_of_element = len(picture[0])
number_of_asterisks = length_of_element + 2
new_list = ['*' * number_of_asterisks for i in range(0, 2)]
new_list.insert(len(new_list)//2, [value for value in picture])
return new_list
I know that my code is good. I just want to know what tweaks I need to make.
a = ['****', '****']
b = ['abc', 'efg']
mid_index = len(a)//2 # Integer result for a division
result = a[:mid_index] + b + a[mid_index:]
If you want to assign the result to a directly, You can also simply:
a[mid_index:mid_index] = b
This question already has answers here:
How do I remove duplicates from a list, while preserving order?
(30 answers)
Closed 2 years ago.
s = "aadarsh , aravind aadarsh,"
st=s.split()
lst=[]
for i in st:
if i not in lst:
lst.append(i)
print(' '.join(lst))
this is my program but am not able to get my desired output
My sample string is
s = "aadarsh , aravind aadarsh,"
and my output should be -> aadarsh , aravind
and all the duplicates should be removed including commas as well how to do it.
The issue seems to be with the fact that split should sometimes work with a comma, and sometimes with a space. Use re.split instead:
s = "aadarsh , aravind aadarsh,"
st=re.split("[\s,]+", s)
lst=[]
for i in st:
if i and i not in lst:
lst.append(i)
print(' '.join(lst))
==> aadarsh aravind
An even simpler solution would be to use a set:
s = "aadarsh , aravind aadarsh,"
# (use comprehension to drop empty strings)
lst = [x for x in set(re.split("[\s,]+", s)) if x]
print(' '.join(lst))
This question already has answers here:
Capitalise every other letter in a string in Python? [closed]
(5 answers)
Closed 3 years ago.
I want the program to return ' mahir ' as 'MaHiR', I have got MHR but how do I get 'a' and 'h' at their usual place ?
I have already tried slicing but that does not work
s = 'mahir'
a = list (s)
c = a[0:5:2]
for i in range (len(c)):
print (c[i].capitalize(),end = " ")
Python's strings are immutable, calling c[i].capitalize() will not change c[i], and therefore will not change s, to modify a string you must create a new one out of it, you can use str.join with a generator expression instead:
s = 'mahir'
s = ''.join(c.upper() if i % 2 == 0 else c for i, c in enumerate(s))
print(s)
Output:
MaHiR
If you want to do it using slicing, you could convert your string to a list since lists are mutable (but the string approach above is better):
s = 'mahir'
l = list(s)
l[::2] = map(str.upper, l[::2])
s = ''.join(l)
print(s)
Output:
MaHiR
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.
This question already has answers here:
How can I find all common letters in a set of strings?
(2 answers)
Closed 8 years ago.
I need to make a function that takes two string arguments and returns a string with only the characters that are in both of the argument strings. There should be no duplicate characters in the return value.
this is what I have but I need to make it print things only once if there is more then one
def letter(x,z):
for i in x:
for f in z:
if i == f:
s = str(i)
print(s)
If the order is not important, you can take the intersection & of the set of characters in each word, then join that set into a single string and return it.
def makeString(a, b):
return ''.join(set(a) & set(b))
>>> makeString('sentence', 'santa')
'nts'
Try this
s = set()
def letter(x,z):
for i in x:
for f in z:
if i == f:
s.add(i)
letter("hello","world")
print("".join(s))
It will print 'ol'
If sets aren't your bag for some reason (perhaps you want to maintain the order in one or other of the strings, try:
def common_letters(s1, s2):
unique_letters = []
for letter in s1:
if letter in s2 and letter not in unique_letters:
unique_letters.append(letter)
return ''.join(unique_letters)
print(common_letters('spam', 'arthuprs'))
(Assuming Python 3 for the print()).