I am studying Python and I got curious about string formatting.
I learned that there is a list comprehension to manipulate or create a list in Python.
For example,
li1 = [i for i in rage(10)]
# this will create a list name with li1
# and li1 contains following:
print(li1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
So, my question is, if I have the code below, is there any solution to solve this? Like using list comprehension?
# The task I need to do is remove all the pucntuations from the string and replace it to empty string.
text = input() # for example: "A! Lion? is crying..,!" is given as input
punctuations = [",", ".", "!", "?"]
punc_removed_str = text.replace(p, "") for p in punctuations
# above line is what I want to do..
print(remove_punctuation)
# Then result will be like below:
# Output: A Lion is crying
There isn't string comprehension, however you can use generator expression, which is used in list comprehension, inside join()
text = ''.join(x for x in text if x not in punctuations)
print(text) # A Lion is crying
Python already has a complete set of punctuations in the standard library.
from string import punctuation
punctuation returns strings !"#$%&'()*+,-./:;<=>?#[]^_`{|}~.
Docs
So you can create a list from your given input which checks whether or not each characters from your input is in the punctuation string.
>>> [char for char in text if char not in punctuation]
['A', ' ', 'L', 'i', 'o', 'n', ' ', 'i', 's', ' ', 'c', 'r', 'y', 'i', 'n', 'g']
You can pass the resulting list in the built-in str.join method.
>>> "".join([char for char in text if char not in punctuation])
'A Lion is crying'
Related
I use this code:
test_list = ['A','a','word','Word','If,','As:']
for a in test_list:
str(a)
a.rstrip('.' or '?' or '!' or '"' or ":" or ',' or ';')
a.lower()
print(a)
print(test_list)
I got result like this:
A
a
word
Word
If,
As:
['A', 'a', 'word', 'Word', 'If,', 'As:']
An I was looking for something like:
a
a
word
word
if
as
['a','a','word','word','if','as']
I want to convert all elements in a list and strip all the marks off, so only if the word for me to process.
The following should do everything you requested by using a generator expression:
# Test List
test_list = ['A', 'a', 'word', 'Word', 'If,', 'As:']
# Remove certain characters and convert characters to lower case in test list
test_list = [str(a).strip('.?!":,;').lower() for a in test_list]
# Print test list
print(test_list)
Output:
['a', 'a', 'word', 'word', 'if', 'as']
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.
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.
I'm looking for a simple way of taking input from the user and placing it into a list of single character elements.
For example:
Input: word2
List = ['w', 'o', 'r', 'd', '2']
Use input to take input:
>>> word = input()
word2 <--- user type this.
>>> word
'word2'
Use list to conver a string into a list containg each character.
>>> list(word)
['w', 'o', 'r', 'd', '2']
This works because list accepts any iterable and string objects is iterable; Iterating a string yield each character.
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.