This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
We just started working with string in my CSCI class, but I'm confused with a recent assignment.
You are given a long string:
"""Justin$Calculus$90$Java$85$Python88$
Taylor$Calculus$73$Java$95$Python86$
Drew$Calculus$80$Java$75$Python94$
"""
The string has three lines. It contains three students’ scores of
three courses. Write a function findScore(student, subject). When
you call the function such as findScore(‘Drew’,’Java’), the function
prints “Drew got 75 of the course Java.”
In addition to the function findScore(student, subject), you can
write other functions. All the functions are inside one program.
I would assume that I need to assign this string to a variable, but do I use one variable, or one for each line?
Any ideas of a start would be greatly appreciated. I'm new to python so bear with me. Also, what is the significance of the $ signs?
have a look at str.split. You can use it to split a string up into a list:
"foo bar baz".split() #['foo','bar','baz'] (split on any whitespace)
"foo$bar$baz".split('$') #['foo','bar','baz']
From here, it's just a matter of splitting the string into the appropriate lists, and then iterating over the lists properly to pick out the elements that you need.
Additionally, you could use str.find to get the index of the class name and split your string there using slicing before splitting on $. That would make it easier to get the particular score (without an additional iteration):
s = 'foo$bar$baz'
s_new = s[s.find('bar'):] #'bar$baz'
baz = s_new.split('$')[1]
print baz
A convenient way to read this would be to use the csv module. It's intended for Comma Separated Values, but you can change the delimiter and use $ instead.
You would need to use delimiter='$' as an argument to your reader.
store string in a variable, say:
strs="""Justin$Calculus$90$Java$85$Python88$
Taylor$Calculus$73$Java$95$Python86$
Drew$Calculus$80$Java$75$Python94$
"""
loop over strs.split() using a for loop , i.e for line in strs.split()
(using strs.split() will return a list containing all lines, splitted at whitespace)
now for each line use line.rstrip("$").split('$'), it'll return something like this for the first line:
['Justin', 'Calculus', '90', 'Java', '85', 'Python88']
rstrip("$") will remove the rightmost $ from the line
Related
This question already has answers here:
How to get the size of a string in Python?
(6 answers)
Closed 1 year ago.
we have just begun our unit on recursion, and I had a question regarding non-recursive functions and strings
I understand that strings are inherently recursive, as each character within a string has its own positive or negative index value, but I am a little unclear on how to create this function.
EDIT: Please disregard above text
What I meant to say:
I understand that a sequence is recursive in nature, that a string is a character followed by another string, just as a list is an element followed by another list.
Imagine we had a function called:
def flipside(s)
And when we input a string into our s parameter of the function, for example, the string:
'homework'
It takes the first half of the string (s) and moves it to the back while taking the second half of the string moving it the front, effectively generating the output:
'workhome'
I guess what I am having an issue with, is regarding string operations. If I do not know the length of s because it can take on any value due to it being a parameter, how do I create a non-recursive program to take 1//2 of s and move that half of the string to the back while simultaneously pushing the second half forward.
I have only gone so far as to set my base case:
def flipside(s):
if s == (''):
return 0
else:
fliprest =
return fliprest
Thank you, I would appreciate any information on the thought process behind your logic, or any feedback regarding any bad habits that I may be developing with how I have started off my code.
You can use slicing
def flipside(s):
return s[len(s)//2:] + s[:len(s)//2]
>>> flipside('homework')
'workhome'
This question already has answers here:
How to calculate an equation in a string, python
(2 answers)
Closed 2 years ago.
I'm using Python 3.7.4. I was wondering about how to keep track of symbols like: +, /, -, * in a string. But I mean with out the '' and "" in front and behind of it. I'm creating a calculator as my project. This is what it looks like:
When ever you click on one of the buttons it adds that number to a string like user_text = ''. So like a blank string. So say you have in 9 + 9 the string when ever you added it together you get 18. But the problem lies with: +, /, -, *. Cause I know how to turn a string into a number and then add them together or any other way. But, how would you keep track of the symbols in the string and add the numbers in the string to each other with the symbol with it. So, with the correct operation.
I've tried to do: if '+' in len(user_text): print("Yes") but then I realize that it can't iterate a string for int. Anything with range is out of the question I realized too. I was thinking about having like a back up line, but as a list then append what ever was entered onto the list. Then keep track of it. Like say user_list = [] then you added 4 + 4 onto the list user_list = ['4', '+', '4']. But then again how would I keep track of the symbols I said, but then add the 2 strings numbers together as an int to get 8. I just can't think of a way to do something like this. I might be overthinking this but I just can't think of it.
If I can provide anymore information on my issue or anything, let me know. I appreciate the advice and help. Thank you.
Have you considered using python's eval()? Since your calculator probably doesn't use the same operator symbols as python you might have to tweak the resulting string from your calculator to make it work, but it sounds like eval() should do the job for you.
I am having trouble wrapping my head around how I would extract the float values from a complex text file in Pymel. I am not a programmer, I am an artist, however I am in need of creating a script for a specific workflow process and I have a beginner level knowledge of python.
My goal: to create objects in 3D space with (x,y,z) coordinates parsed from a specific text file from another program.
Ex. of text file:
point 1 8.740349 -4.640922 103.950059
point 2 8.520906 3.447561 116.580496
point 3 4.235010 -7.562914 99.632423
etc., etc
there's much more space in my text file between the point #'s and the vector floats.
I want to create a dictionary that I will use to create my objects in my 3D program.
For example,
myDictionary = {(point 1),[8.740349,-4.640922,103.950059]), etc. }.
This is my code snippet so far:
def createLocators():
global filePath
global markerNum
global markerCoord
print "getting farther! :)"
with open(filePath,'r') as readfile:
for line in readfile:
if "point" in line:
Types = line.split(' ')
markerNum = [Type[1] for Type in Types]
markerCoord = [Type[2] for Type in Types]
print markerNum, markerCoord
As you can see in the code, the space between the information is long. I figure if I can remove that space I can get two data sets that will be easier to work with. There is also many more lines in the text document that I don't care about, hence the if statement to filter only lines that start with "point". When I run createLocator() to test to see if it's splitting up the lines into my two lists it runs fine, but the print looks empty to me.
ex.
[' '] [' ']
I've tried googling and searching answers here on SO, and searching both Pymel and regular python documentation for what I'm doing wrong or better approaches, but I have to admit the extent of my knowledge ends here.
What am I doing wrong? Is there a better and more efficient way to extract the data I need that I'm missing?
Thanks for reading!
First, you probably do not want to be splitting on that massive string of spaces. In fact what you almost certainly want is to just use line.split() with no arguments, as this will split apart all text on any kind, and any amount, of whitespace. i.e:
>>> 'A B C\t\n\t D'.split()
['A', 'B', 'C', 'D']
Then, assuming the format you've shown is correct, you should need need to get Types[2:5], i.e. the second, third, and fourth elements of Types, for the coordinates.
Beyond this, you should not be using capital names for local variables, and you should not be using global variables. Use function arguments instead, and rename Types to split_line or something.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reverse a string in Python
Its been stumping me despite my initial thoughts that it would be simple.
Originally, I thought I would have have it print the elements of the string backwards by using slicing to have it go from the last letter to the first.
But nothing I've tried works. The code is only a couple lines so I don't think I will post it. Its extraordinarily frustrating to do.
I can only use the " for ", "while", "If" functions. And I can use tuples. And indexing and slicing. But thats it. Can somebody help?
(I tried to get every letter in the string to be turned into a tuple, but it gave me an error. I was doing this to print the tuple backwards which just gives me the same problem as the first)
I do not know what the last letter of the word could be, so I have no way of giving an endpoint for it to count back from. Nor can I seem to specify that the first letter be last and all others go before it.
You can do:
>>> 'Hello'[::-1]
'olleH'
Sample
As Mike Christensen above wrote, you could easily do 'Hello'[::-1].
However, that's a Python-specific thing. What you could do in general if you're working in other languages, including languages that don't allow for negative list slicing, would be something more like:
def getbackwards(input_string):
output = ''
for x in range(0,len(input_string),-1):
output += input_string[x]
return output
You of course would not actually do this in Python, but just wanted to give you an example.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Hi I'm trying to reverse a string with the following code. Does anyone see the bug here?
def reverse(string):
length = len(string)
last = length -1
middle = length/2
newstring = []
for i in range(middle):
newstring[i] = string[last -i]
newstring[last -i] = string[i]
return ''.join(newstring)
There are multiple bugs:
You can't index into an empty list: newstring[i] and newstring[last -i].
You always add characters in pairs, so the result (if other bugs are fixed) always has an even length, even if the input string had an odd length.
There may be more.
Lastly, I think you're making it too hard for yourself:
In [1]: 'abcdef'[::-1]
Out[1]: 'fedcba'
This uses the slicing syntax, which is start:stop:step. By omitting start and stop we're taking the entire string, and step=-1 simply means that we're taking the characters in reverse order.
You can't do newstring[last-i], right? That should return an index error.
How about this one:
def reverse(string):
tmp=[]
for c in string:
tmp.insert(0,c)
return ''.join(tmp)
You're going out of range because you're directly assigning to an index of an empty list. On the first pass you reference the nonexistent newstring[0].
Do not use the name "string". It is the name of a common Python module that you may end up importing. Looking at this, most people wouldn't know if you were referring to the module here or not.
If you want to do the whole manual list manipulation thing for the sake of pedagogy, you're better off treating the source string as a stack and the destination list as a queue, popping off the source and enqueueing on the destination:
def reverse(source):
source = list(source)
dest = []
while source:
dest.append(source.pop())
return ''.join(dest)
In general, you shouldn't have to use numeric indexing in Python for operations that affect the entire collection uniformly. If you find yourself in that situation you're most likely thinking too low-level.
I would personally use extended slice notation:
"hello world"[::-1]
Leaving off the first argument of a slice means "the beginning of the list". Leaving off the second argument of a slice means "the end of the list". The third argument represents the step by which the list is traversed. By stepping negatively you traverse the list in reverse.
Another way is:
"".join(reversed("abc"))
But probably is not as efficient as aix's Method to reverse a string.