This question already has answers here:
How do I save results of a "for" loop into a single variable? [duplicate]
(2 answers)
Closed 1 year ago.
I have written a code that prints all letters, but I want to take its output to put it in a variable. i.e. I want to take all letters and save it in one variable instead of writing all letters manually.
for letter in range(97, 123):
letters = chr(letter)
print(letters, end=" ")
If you wish to complete this in one line, Python has a neat way of allowing you to create lists with the use of list comprehensions. If you wish to know more about what a list comprehension is, you may see point 5.1.3 here.
letters = [chr(letter) for letter in range(97, 123)]
A more comprehensible way of solving the problem is to append the characters to a letters list which should be defined before you begin to loop your range.
letters = []
for letter in range(97, 123):
letters.append(chr(letter))
print(letters)
The Python documentation does a good job of explaining the different data structures used throughout the programming language, I hope this clears up the various ways to solve your problem described.
Related
This question already has answers here:
Python find elements in one list that are not in the other [duplicate]
(10 answers)
Closed last year.
Im new to coding and am looking for some help.
I need to remove words of a small list from a large list.
clean_book = [word for word in bwords_split if word in words_list]
I used the line above where bwords_split is the larger list and words_list is the smaller list and clean_book is the result. I think I'm thinking to arthemetically. Could someone help me?
Your solution looks fine. Just change the second "in" to "not in"
This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Closed last year.
import time
while True:
npc=input("Josuke\n\nJotaro Kujo (Part 4)\n\nChoose NPC to talk to.")
if npc=="Josuke" or npc=="josuke":
confirm=input("[Press E to interact.]")
elif npc=="jp4" or npc=="JP4" or npc=="Jp4
Within this code you can see that there are 2 NPCs to interact to. Because there are many ways of addressing the name Jotaro Kujo (Part 4), the if statement has many "or"s, but I want to be able to condense it. Could I use an array to be able to put the possibilities in and then have the if statement identify if the value is within the array? (I haven't completed the code yet, but the problem doesn't require the full code to be completed.)
Yes, you can do it easily using the in operator to check if a particular string is in the list.
as an example:
lst = ["bemwa", "mike", "charles"]
if "bemwa" in lst:
print("found")
And if all the possibilities you want to cover are related to case-insensitivity you can simply convert the input to lower-case or upper-case and compare it with only one possibility.
This question already has answers here:
How to match a whole word with a regular expression?
(4 answers)
Closed 2 years ago.
I want to find just numbers in textfile so I made this code
r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?"
but I also get and numbers from string with characters (e.g. my txt file include string a278, and it also find number 278, so I want to not find that kind of numbers)
I want to find just "clear numbers", not a numbers from string which include char.
You can consider look at wordboundaries.
https://www.regular-expressions.info/wordboundaries.html
You could solve such a problem with list comprehension, even without regex, as a simpler solution.
Would have been beneficial if you'd gave us an idea of the type of data you're dealing with i/e of your input data.
Either way considering what you've stated, you want only numbers to be detected without string numbers.
case = "test123,#213 12" output = [int(i) for i in case .split() if i.isdigit()]
output Out[29]: [12]
This question already has answers here:
Python for-in loop preceded by a variable [duplicate]
(5 answers)
Closed 6 years ago.
I'm new to python, and I'm trying to understand the following line:
"".join(char for char in input if not unicodedata.category(char).startswith('P'))
Source: https://stackoverflow.com/a/11066443/3818487
This code removes all unicode punctuation from input. I don't understand why it works. As far as I can tell, it just iterates over all characters in input ignoring the punctuation characters. How can it access char before it is declared in the for loop? I come from a java background, so this is very confusing to me.
This comprehension would look more like the following, in regular code (using a list to store our non-punctuation characters).
#input is defined somewhere prior to the loop
output = []
for char in input:
if not unicodedata.category(char).startswith('P'):
output.append(char)
''.join(output)
Comprehensions iterate over the loop portion first, with the value being iterated over on the left.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python’s most efficient way to choose longest string in list?
I have a list L
L = [[1,2,3],[5,7],[1,3],[77]]
I want to return the length of the longest sublist without needing to loop through them, in this case 3 because [1,2,3] is length 3 and it is the longest of the four sublists. I tried len(max(L)) but this doesn't do what I want. Any way to do this or is a loop my only way?
max(L,key=len) will give you the object with the longest length ([1,2,3] in your example) -- To actually get the length (if that's all you care about), you can do len(max(L,key=len)) which is a bit ugly -- I'd break it up onto 2 lines. Or you can use the version supplied by ecatamur.
All of these answers have loops -- in my case, the loops are implicit which usually means they'll be executed in optimized native machine code. If you think about it, How could you know which element is the longest without looking at each one?
Finally, note that key=function isn't a feature that is specific to max. A lot of the python builtins (max,min,sorted,itertools.groupby,...) use this particular keyword argument. It's definitely worth investing a little time to understand how it works and what it typically does.
Try a comprehension:
max(len(l) for l in L)