Removing all elements containing (",") from a list - python

muutujad = list(input("Muutujad (sisesta formaadis A,B,C,...): "))
while "," in muutujad == True:
muutujad.remove(",")
print (muutujad)
My brain says that this code should remove all the commas from the list and in the end
the list should contain only ["A","B","C" ....] but it still contains all the elements. When i tried to visualize the code online, it said like [ "," in muutujad ] is always False but when i check the same command from the console it says it is True. I know it is a simple question but i would like to understand the basics.

You can use a list comprehension instead of a while loop:
muutujad = [elem for elem in muutujad if elem != ',']
Your if test itself is also wrong. You never need to test for == True for if in any case, that's what if does. But in your case you test the following:
("," in muutujad) and (muutujad == True)
which is always going to be False. In python, comparison operators like in and == are chained. Leaving off the == True would make your while loop work much better.
I'm not sure you understand what happens when you call list() on a string though; it'll split it into individual characters:
>>> list('Some,string')
['S', 'o', 'm', 'e', ',', 's', 't', 'r', 'i', 'n', 'g']
If you wanted to split the input into elements separated by a comma, use the .split() method instead, and you won't have to remove the commas at all:
>>> 'Some,string'.split(',')
['Some', 'string']

The best option here is to simply parse the string in a better way:
>>> muutujad = input("Muutujad (sisesta formaadis A,B,C,...): ").split(",")
Muutujad (sisesta formaadis A,B,C,...): A, B, C
>>> muutujad
['A', ' B', ' C']
str.split() is a much better option for what you are trying to do here.

What about list("Muutujad (sisesta formaadis A,B,C,...): ".replace(' ', ''))
Downvoter: I meant: this is how you do remove commas from string.
You do not convert your input from string to list and then remove your commas from the list, it's absurd.
you do: list(input('...').replace(' ', ''))
or you use split, as pointed out above.

Related

Recreating the strip() method using list comprehensions but output returns unexpected result

I am trying to 'recreate' the str.split() method in python for fun.
def ourveryownstrip(string, character):
newString = [n for n in string if n != character]
return newString
print("The string is", ourveryownstrip(input("Enter a string.`n"), input("enter character to remove`n")))
The way it works is that I create a function that passes in two arguments: 1) the first one is a string supplied, 2) the second is a a string or char that the person wants to remote/whitespace to be moved from the string. Then I use a list comprehension to store the 'modified' string as a new list by using a conditional statement. Then it returns the modified string as a list.
The output however, returns the entire thing as an array with every character in the string separated by a comma.
Expected output:
Boeing 747 Boeing 787
enter character to removeBoeing
The string is ['B', 'o', 'e', 'i', 'n', 'g', ' ', '7', '4', '7', ' ', 'B', 'o', 'e', 'i', 'n', 'g', ' ', '7', '8', '7']
How can I fix this?
What you have set up is checking each individual character in a list and seeing if it matches 'Boeing' which will never be true so it will always return the whole input. It is returning it as a list because using list comprehension makes a list. Like #BrutusForcus said this can be solved using string slicing and the string.index() function like this:
def ourveryownstrip(string,character):
while character in string:
string = string[:string.index(character)] + string[string.index(character)+len(character):]
return string
This will first check if the value you want removed is in your string. If it is then string[:string.index(character)] will get all of the string before the first occurrence of the character variable value and string[string.index(character)+len(character):] will get everything in the string after the first occurrence of the variable value. That will keep happening until the variable value doesn't occur in the string anymore.

Remove duplicates but retain sequence

I'm trying to reduce a string with duplicates however I do not want to create a set. For example
mystring = 'TTTTTPPPTPTTTTPPPPPPPPP'
The sequence of the letters is 'TPTPTP', so I need a resulting string of
newstring = 'TPTPTP'
I'm sure there is an easy one-liner but its evading me
You're looking for itertools.groupby.
>>> mystring = 'TTTTTPPPTPTTTTPPPPPPPPP'
>>> groups = [x for x, y in itertools.groupby(mystring)]
>>> groups
['T', 'P', 'T', 'P', 'T', 'P']
>>> ''.join(groups)
TPTPTP
Official documentation
zip each character with the one before and take those which are different:
>>> a
'TTTTTPPPTPTTTTPPPPPPPPP'
>>> ''.join(i for i, j in zip(a, '\0' + a) if i != j)
'TPTPTP'
You can also use regular expressions if you feel like it.
>>> import re
>>> mystring = 'TTTTTPPPTPTTTTPPPPPPPPP'
>>> ''.join(re.findall(r'(.)\1*', mystring))
'TPTPTP'
That looks for any character, followed by the same found character zero or more times.

Isolating letters in a string and converting them to a list

I want to be able to isolate the letters in a string from an input and return them as a collection containing 4 separate lower case characters.
This is what I have so far:
def main():
original = input(str("Enter a 4-letter word: "))
letters = isolate_letters(original)
def isolate_letters(original):
letters = list(original.items())
return letters
main()
>>> s = "1234"
>>> list(s)
['1', '2', '3', '4']
You want the first 4 lowercase characters:
letters = [c for c in original.lower() if c.isalpha()][:5]
str.isalpha
str.lower
First you convert the string to lowercase (lower()), then pick out all the alphabet characters from the string (isalpha()) and finally slice off the first 4 ([:5])
I presume you want to filter for the ascii letters. If not, a python string is iterable, so for most practical applications a string behaves just like a list - try just using the string as if it was a list.
If you want all letters:
>>> import string
>>> original = "foo, bar, 2014"
>>> letters = [c for c in original if c in string.ascii_letters]
['f', 'o', 'o', 'b', 'a', 'r']
If you want them without repetitions:
>>> unique_letters = set(letters)
>>> unique_letters
{'a', 'b', 'f', 'o', 'r'}
[update]
Thanks a lot! im new to python is there any chance you could explaiin how this works please?
Well, string.ascii_letters contains:
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
We are using Python list comprehensions, a syntax based on the set-builder notation in math:
[item for item in some_list if condition]
It is almost plain english: return a list of items in some_list if condition is true. In our case, we are testing if the character is an ascii letter using the in operator.
The set object in Python is an unordered list that ensure there is no repeated items.

How To Add List Elements and Convert Them To A String

I am attempting to write a function that turns a string of lower case letters into a string of all capital letter. I'm trying to use reduce and map() to do this, though a list comprehension instead of map would be alright too.
Use str.upper():
>>> 'How are you?'.upper()
'HOW ARE YOU?'
Regarding your question "I can't figure out how to put them back together from the list into strings", use str.join:
>>> lis = ['H', 'O', 'W', ' ', 'A', 'R', 'E', ' ', 'Y', 'O', 'U', '?']
>>> ''.join(lis)
'HOW ARE YOU?'
If you want to use reduce, you need to give it an initial value of '' and give it a function that takes two arguments and reduces them to a single result:
>>> reduce(lambda s,t:s + t, lis, '')
'HOW ARE YOU?'
reduce without lambda:
>>> import operator
>>> reduce(operator.add, lis, '')
'HOW ARE YOU?'
important note: Using reduce to build a string is very inefficient because it creates a new string after each addition. The performance for even medium length strings would be excessive.

One word string made into a list of the letters

I have a list of words but I need to take the last item off the list, perform a function with the rest of the list then replace the last item. But for some reason when i go to to replace the last item, it does this...
>>> List = ['this', 'is', 'a', 'list']
>>> last = List[-1]
>>> others = List[:-1]
>>> others += last
>>> print others
['this', 'is', 'a', 'l', 'i', 's', 't']
Is there any way I can concatenate the list called last onto others but have it just one single element.
Try using append
others.append(last)
You can further simplify the code by doing this:
last = List.pop()
This removes the last element or List if no parameter is specified, and saves it in the variable last for you
Use append instead of +=:
>>> others.append(last)
Use:
others.append(last)
instead of
others += last
This is because:
When you are doing
list += ["somethingHere"]
it's equivalent to
list.extend(["somethingHere"])
According to the doc,
list.extend(L) = Extend the list by appending all the items in the given list
but
list.append(x) = Add an item to the end of the list
And what you need here is to " add an item " not to " append all the items in the given list " (all characters in this case.)
Please use one following:
others += [last]
others.append(last)
+ for list instances is iterating over element being added to it, thus iterating over string you get list of characters.
others += 'string'
others += ['s', 't', 'r', 'i', 'n', 'g']

Categories