This question already has answers here:
Understanding slicing
(38 answers)
Closed 2 years ago.
I need your help, can anyone tells me that what this part of code is doing?
if line[-6:] == '[edit]':
state = line[:-6]
and
town = line[:(line.index('(')-1)]
the whole code is :
def get_list_of_university_towns():
'''Returns a DataFrame of towns and the states they are in from the
university_towns.txt list. The format of the DataFrame should be:
DataFrame( [ ["Michigan", "Ann Arbor"], ["Michigan", "Yipsilanti"] ],
columns=["State", "RegionName"] )
The following cleaning needs to be done:
1. For "State", removing characters from "[" to the end.
2. For "RegionName", when applicable, removing every character from " (" to the end.
3. Depending on how you read the data, you may need to remove newline character '\n'. '''
with open('university_towns.txt') as file:
data = []
for line in file:
data.append(line[:-1])
# print(data)
state_town = []
for line in data:
if line[-6:] == '[edit]':
state = line[:-6]
# print(state)
elif '(' in line:
town = line[:(line.index('(')-1)]
# print(town)
state_town.append([state,town])
else:
town = line.rstrip()
state_town.append([state,town])
# print(state_town)
ans = pd.DataFrame(state_town, columns = ['State','RegionName'])
return ans
get_list_of_university_towns()
if line[-6:] == '[edit]':
state = line[:-6]
Is simply checking if last 6 character of given string are a [edit], if so then this value is assigned to a state var.
town = line[:(line.index('(')-1)]
Here the town var gets the value of a characters of a line that are in front of ( excluding.
EDIT:
Lets split this like:
index_to_par = line.index('(')
town = line[:(index_to_par - 1)]
So index_to_par is getting index on line string of a first (
Example if we have string like some string (example) then we get a value of 12 because ( is on a 12 place of this string.
Then we assing to a town a slice of this line as line[:(index_to_par - 1)] - we want to have values from begining of the string (as there is no value in front of :) to a our index_to_par - 1 (so all values before first occurence of (). You can read more about string sliceing here ---> https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3
Related
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
Below is the prompt I am having trouble with. I have come up with a solution that pretty much gets the proper output, but with an extra return/new line that should be a space and not a new line. Can anyone see what could be causing the new line?
Write a program that gets a list of integers from input, and outputs non-negative integers in ascending order (lowest to highest).
Ex: If the input is:
10 -7 4 39 -6 12 2
the output is:
2 4 10 12 39
For coding simplicity, follow every output value by a space. Do not end with new line.****
My Code:
#Get Input
user_input = input()
#Split input into individual entries within list
user_list = user_input.split()
map_object = map(int, user_list)
list_of_integers = list(map_object)
#Remove Negative Values from list
list_of_integers = [i for i in list_of_integers if i >= 0]
#Sort List In Ascending Order
list_of_integers.sort()
#Convert list of integers back into a string
list_of_integers = [str(int) for int in list_of_integers]
#Join string by a space
str_of_ints =" ".join(list_of_integers)
print(str_of_ints)
If you want to remove the newline from the print you can just do this
print(str_of_ints, end='') # end character is now empty not \n
This question already has answers here:
How to check if a string is a substring of items in a list of strings
(18 answers)
Closed 1 year ago.
Here is my code. It gets a list of hashes, which are leaked. I want to check my password against it. What I want it to do, is to, when it finds it to throw me back the number of occurrences it has been leaked, if at all. How can this be accomplished?
For example sake, let's say our necessary hash happens to be the 2nd one and thus we want to extract the number 3.
What we have already is the hash infront of it. It is named "ending" as you can see in the code.
import hashlib
import requests
password = input("Enter password: ")
encoded_str = password.encode()
hash_obj = hashlib.sha1(encoded_str)
hashed = hash_obj.hexdigest().upper()
beginning = hashed[:5]
ending = hashed[5:].strip()
response = requests.get("https://api.pwnedpasswords.com/range/"+beginning)
output = response.text
listing = output.split()
print(listing)
output:
['0015711CF2308DD93DC449B888F9805B728:1', '0083F4473656452B43073DF2861FD289F63:3', '0DE17FB8EC56DD673FF3AF94BAB5029BFF2:1', '0DEC778F27B49DECF0E7C3B8AB2DD152990:15', '0E8EEF1620F095A7A26F679388A02EFEA4C:2', '0FD09EF75E6654D1E2FB5FC715A11331B6D:2', '11CFB41389B28F08B74A17851292D086922:1', '12A7DE6568963683AA7D21E3FBA1A1B5D39:1', '12B602E54A280622E21FC57607D70F9E3D6:4', '133B5AFB8798339FF1BF29DBBD068DFB556:2912', '13723F1F53E4468943870CA48E2093C0531:5', '139946DFB7AA0936F96DFB9B27931508AC3:1', '13AB10DBA939781F0416361A25024EF0D8C:4', '13E2A779A5F3F6C4BA21F23A5FB949DE347:2', '52CFB9745616A23A369EA5AD9D480DFE8E9:1', '52F07FB24866744C9E7D7460A04C143AAA3:2']
Our goal output:
3
try to use this code:
num = 0
for line in listing:
if ending in line:
num = line.split(':')[1]
break
else:
print("the 'ending' is not in 'listing'")
This question already has answers here:
Find string between two substrings [duplicate]
(20 answers)
Closed 2 years ago.
If you were to have a string of characters/numbers in a sequence - say AACBDEFZZBGFAAFFGGCCEEZZ
How could you iterate over the string, and then have every character between the AA and ZZ appear in a list? The end result in this case being:
[CBDEF], [FFGGCCEE] ?
Thanks
You can use str.index:
def between_markers(s, starting_marker="AA", ending_marker="ZZ"):
# keep track of where the previous marker was found
prev_ind = 0
ret = []
while True:
try:
# find the starting marker
start = s.index(starting_marker, prev_ind) + len(starting_marker)
# find the ending marker
end = s.index(ending_marker, start)
prev_ind = end + len(ending_marker)
# slice and append to return list
ret.append(s[start:end])
except ValueError:
# couldn't find one of the two markers so we're done
break
return ret
between_markers("AACBDEFZZBGFAAFFGGCCEEZZ") # ['CBDEF', 'FFGGCCEE']
[Code below question]
The idea is to expand on python's built-in split() function. This function takes two strings, one that needs to be split, and the second is what characters to omit and split at in the first string. This code has worked, but for some reason with this input, it will not iterate anything past the last comma. In other words, no matter the input in this format, it won't append anything past the final comma. I can't figure out why. I have gone line through line of this code and I can't find out where I am losing it.
Why is my code not iterating through any characters past the last comma?
def split_string(source,splitlist):
## Variables ##
output = []
start, start_pos , tracker = 0 , 0 , 0
## Iterations ##
for char in source:
start = source.find(char,start)
if char in splitlist:
tracker += 1
if tracker <= 1:
end_pos = source.find(char, start)
output.append(source[start_pos:end_pos])
start_pos = end_pos + 1
else:
start_pos+=1
else:
tracker = 0
return output
out = split_string("First Name,Last Name,Street Address,City,State,Zip Code",",")
print out
Because your code does not have any code to append from the last comma till the end of string.
end_pos = source.find(char, start)
output.append(source[start_pos:end_pos])
Your need to finally append a range between last comma and string length.
Add the following after the loop ends.
output.append(source[end_pos+1:];
Modified code:
http://ideone.com/9Khu4g
This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
How to concatenate (join) items in a list to a single string
(11 answers)
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed 8 months ago.
The aim of the following program is to convert words in 4 characters from "This" to "T***", I have done the hard part getting that list and len working.
The problem is the program outputs the answer line by line, I wonder if there is anyway that I can store output back to a list and print it out as a whole sentence?
Thanks.
#Define function to translate imported list information
def translate(i):
if len(i) == 4: #Execute if the length of the text is 4
translate = i[0] + "***" #Return ***
return (translate)
else:
return (i) #Return original value
#User input sentense for translation
orgSent = input("Pleae enter a sentence:")
orgSent = orgSent.split (" ")
#Print lines
for i in orgSent:
print(translate(i))
On py 2.x you can add a , after print:
for i in orgSent:
print translate(i),
If you're on py 3.x, then try:
for i in orgSent:
print(translate(i),end=" ")
default value of end is a newline(\n), that's why each word gets printed on a new line.
Use a list comprehension and the join method:
translated = [translate(i) for i in orgSent]
print(' '.join(translated))
List comprehensions basically store the return values of functions in a list, exactly what you want. You could do something like this, for instance:
print([i**2 for i in range(5)])
# [0, 1, 4, 9, 16]
The map function could also be useful - it 'maps' a function to each element of an iterable. In Python 2, it returns a list. However in Python 3 (which I assume you're using) it returns a map object, which is also an iterable that you can pass into the join function.
translated = map(translate, orgSent)
The join method joins each element of the iterable inside the parentheses with the string before the .. For example:
lis = ['Hello', 'World!']
print(' '.join(lis))
# Hello World!
It's not limited to spaces, you could do something crazy like this:
print('foo'.join(lis))
# HellofooWorld!
sgeorge-mn:tmp sgeorge$ python s
Pleae enter a sentence:"my name is suku john george"
my n*** is s*** j*** george
You just need to print with ,. See last line of below pasted code part.
#Print lines
for i in orgSent:
print (translate(i)),
For your more understanding:
sgeorge-mn:~ sgeorge$ cat tmp.py
import sys
print "print without ending comma"
print "print without ending comma | ",
sys.stdout.write("print using sys.stdout.write ")
sgeorge-mn:~ sgeorge$ python tmp.py
print without ending comma
print without ending comma | print using sys.stdout.write sgeorge-mn:~ sgeorge$