I am using Python 3.4.1. The purpose of this program is to take a series of elements that the user types in and run them backwards. For example, "Hello" becomes "olleH". I've been trying to get this right for a while now and It's been completely stumping me for quite some time.
word=input("Type any word:")
word_l=len(word)
word2=None
for word in range(word_l):
word2+=word[word_l]-i
print(word2)
Sorry if this seems like a serious noob question. Thanks.
This is a standard indexing problem. There's a third optional argument when you're slicing that creates a step. By setting that step to -1 you reverse the sequence:
>>> word = "hello"
>>> print(word[::-1])
olleh
>>>
Rule of thumb: If you are using string index or list indexes in a loop in Python to access each element -- look at the problem again 'cause there probably is a better way to do it.
You can simply add each character to the string in turn which will reverse the string:
word='Hello'
word2=''
for c in word:
word2=c+word2
print(word2)
You can also just use reversed:
>>> ''.join(reversed('Hello'))
'olleH'
word=input("Type any word:")
word_l=len(word)
word2=''
for i in range(word_l):
word2+=word[word_l-i-1]
print(word2)
Related
Simple question:
I'm new to programming and need to use the command string.count
I know that if I do
a="laringologo"
a.count("o")
it will give me the number of o's in the word.
How can I use the command if I want to count the number of o's after "laringo"?
I know the command works like
string.count(s, sub[, start[, end]] but I don't understand how to use it correctly
You can use the start argument to tell count at which index to start counting. In your case, you want it to start counting after the number of characters in "laringo", so you can do:
a="laringologo"
>>> a.count('o', len("laringo"))
2
#sacul's answer is correct if/when you know that 'laringo' is always at the beginning of a. If it is not, as in the following example, then you should first find it, then skip it, and then count 'o's in the rest of the string:
a = "foobarlaringologo"
a.count('o', a.index('laringo') + len('laringo'))
count() has three attributes string.count(substring, start=…, end=…) If you want to count substrings after a certain number of characters, the syntax would be string.count('substring', numberOfCharacters). If "laringologo" is not necessarily the beginning of the string you can look for it with string.find('substring')
a="laringologo new to programming"
a.count("o", len(laringologo))
#or
b="header laringologo new to programming"
b.count("o", b.find('laringologo')+len('laringologo'))
Given a list of strings as such,
xs = ['1\n','2\n','3\n','4\n','5\n']
sum up the integers to return the sum as a string and append the sum to the list so that the returned list
xs = ['1\n','2\n','3\n','4\n','5\n','Sum:15\n']
I understand the process of going through the list and iterating this, I just don't understand how to get rid of the \n character so that I can only use the integer to find the sum?
def my_fun(x):
return x+["Sum: %s\n"%sum(map(int,x)),]
This uses a generator:
>>> xs + ['Sum:{0}\n'.format(str(sum(int(s) for s in xs)))]
['1\n', '2\n', '3\n', '4\n', '5\n', 'Sum:15\n']
To answer your question a bit more directly (leaving out the iteration since you said that's not the problem):
Believe it or not, int actually ignores the trailing newline when you use it to parse:
>>> int('1\n')
1
Once you have an int, you can do arithmetic as normal.
This is a documented feature in Python 2 and 3:
Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace.
-Python int documentation (emphasis mine)
If you're interested in more streamlined ways of doing the iteration, you can see Joran's answer and the comments on it, but if this is some kind of assignment, I wouldn't use them if I were you. It benefits you more to work through the problems yourself. You of course want to use the more advanced features for professional work.
The task that I have to perform is as follows :
Say I have a list of words (Just an example...the list can have any word):
'yappingly', 'yarding', 'yarly', 'yawnfully', 'yawnily', 'yawning','yawningly',
'yawweed', 'yealing', 'yeanling', 'yearling', 'yearly', 'yearnfully','yearning',
'yearnling', 'yeastily', 'yeasting', 'yed',
I have to create a new list of words from which words having the suffix ing are added after removing the suffix (i.e yeasting is added to the new list as yeast) and the remaining words are added as it is
Now as far as insertion of string ending with ing is concerned, i wrote the following code and it works fine
Data=[w[0:-3] for w in wordlist if re.search('ing$',w)]
But how to add the remaining words to the list?? How do I add an else clause to the above if statement? I was unable to find suitable documentation for the above. I did came across several questions on SO regarding the shorthand if else statement, but simply adding the else statement at the end of the above code doesn't work. How do I go about it??
Secondly, if I have to extend the above regular expression for multiple suffixes say as follows:
re.search('(ing|ed|al)$',w)
How do I perform the "trim" operation to remove the suffix accordingly and simultaneously add the word to the new list??
Please Help.
First, what makes you think you need a regexp at all? There are easier ways to strip suffixes.
Second, if you want to use regexps, why not just re.sub instead of trying to use regexps and slicing together? For example:
Data = [re.sub('(ing|ed|al)$', '', w) for w in wordlist]
Then you don't need to work out how much to slice off (which would require you to keep track of the result of re.search so you can get the length of the group, instead of just turning it into a bool).
But if you really want to do things your way, just replace your if filter with a conditional expression, as in iCodez's answer.
Finally, if you're stuck on how to fit something into a one-liner, just take it out of the one-liner. It should be easy to write a strip_suffixes function that returns the suffix-stripped string (which is the original string if there was no suffix). Then you can just write:
Data = [strip_suffixes(w) for w in wordlist]
Regarding your first question, you can use a ternary placed just before the for:
Data=[w[0:-3] if re.search('ing$',w) else w for w in wordlist]
Regarding your second, well, the best answer in my opinion is to use re.sub as #abarnert demonstrated. However, you could also make a slight adaption to your use of re.search:
Data=[re.search('(.*)(?:ing|ed|al)$', w).group(1) for w in wordlist]
Finally, here is a link for more information on comprehensions.
When I try to use the 'list.count' function on my raspberry Pi it comes up with
Name Error: name 'count' is not defined
Is there any thing I can do about it? Thank you in advance for any help. I am using Python. I am just starting out with Python and in my tutorial it states
>>>count(seq,'a')
With 'seq' being a sequence of letters that I entered earlier. I expect it is meant to count the number of 'a's in the sequence.453
Thank you all very much for your quick responses and answers, I have now fixed the problem. This was my first ever online question that I asked so thank you again. The second answer by Markus Unterwaditzer finally solved the problem with 'seq.count('a')'
Also thanks to DSM for finding the tutorial and explaining why I had my problem. Everything works now and I am back to learning my first computer language.
Ah. The magic in the tutorial is in the
from string import *
line, which is bad practice. It imports everything from the string module into scope, including the function string.count:
>>> print string.count.__doc__
count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation.
count is also a method of strings, so you can write
>>> 'aaa'.count('a')
3
which is generally preferred. In modern Python, the string module doesn't even have a count function.
I expect it is meant to count the number of 'a's in the sequence
Depending on what list is, that's probably not the correct syntax. If list is a string you can do this:
>>>a = "hello"
>>>a.count('h')
1
>>>a.count('l')
2
Works the same for a "list":
>>>a = ['h','e','l','l','o']
>>>a.count('l')
2
>>> seq = ['a', 'b', 'c', 'a']
>>> seq.count('a')
2
>>> type(seq) is list # the reason it's mentioned as list.count
True
>>> list.count(seq, 'a') # the same thing, but nobody does it like that
2
I'm studing Python for one month and I'm trying to make a keygen application by using the dictionary. The idea was to compare each letter in name = input('Name: ') to dict.keys() and print as result dict.values() for each letter of name equal to dict.keys(). That's what I wrote:
name = input('Name: ')
kalg = dict()
kalg['a'] = '50075'
kalg['b'] = '18099'
kalg['c'] = '89885'
etc...
I tryed writing this...
for x in kalg.keys():
print(x)[/code]
...but i need to keep print(x) result but i don't know how to do it! If i do this:
for x in kalg.keys():
a = x
'a' keeps only the last key of the dictionary :(. I thought it was because print(x) prints each key of dict.keys() on a new line but i don't know how to solve it (I tryed by converting type etc... but it didn't work).
Please can you help me solve this? I also don't know how to compare each letter of a string with another string and print dict.values() as result and in the right position.
Sorry for this stupid question but i'm too excited in writing python apps :)
# Karl
I'm studing Python over two differt books: 'Learning Python' by Mark Luts which covers Python
2 and a pocket which covers Python 3. I examined the list comprehension ón the pocket one and Imanaged to write three other variants of this keygen. Now i want to ask you how can I implementthe source code of this keygen in a real application with a GUI which verify if name_textbox andkey_textbox captions match (i come from basic so that was what i used to write, just to give youan idea) as the keygen output result. I know i can try to do this by my own (I did but with nosuccess) but I would like to first complete the book (the pocket one) and understand all the mainaspects of Python. Thank you for the patience.
Calling print can't "keep" anything (since there is no variable to store it in), and repeatedly assigning to a variable replaces the previous assignments. (I don't understand your reasoning about the problem; how print(x) behaves has nothing to do with how a = x behaves, as they're completely different things to be doing.)
Your question boils down to "how do I keep a bunch of results from several similar operations?" and on a conceptual level, the answer is "put them into a container". But explicitly putting things into the container is more tedious than is really necessary. You have an English description of the data you want: "dict.values() for each letter of name equal to dict.keys()". And in fact the equivalent Python is shockingly similar.
Of course, we don't actually want a separate copy of dict.values() for each matching letter; and we don't actually want to compare the letter to the entire set of dict.keys(). As programmers, we must be more precise: we are checking whether the letter is a key of the dict, i.e. if it is in the set of dict.keys(). Fortunately, that test is trivial to write: for a given letter, we check letter in dict. When the letter is found, we want the corresponding value; we get that by looking it up normally, thus dict[letter].
Then we wrap that all up with our special syntax that gives us what we want: the list comprehension. We put the brackets for a list, and then inside we write (some expression that calculates a result from the input element) for (a variable name for the input elements, so we can use it in that first expression) in (the source of input elements); and we can additionally filter the input elements at the same time, by adding if (some condition upon the input element).
So that's simple enough: [kalg[letter] for letter in name if letter in kalg]. Notice that I have name as the "source of elements", because that's what it should be. You explained that perfectly clearly in your description of the problem - why are you iterating over dict.keys() in your existing for-loops? :)
Now, this expression will give us a list of the results, so e.g. ['foo', 'bar', 'baz']. If we want one continuous string (I assume all the values in your dict are strings), then we'll need to join them up. Fortunately, that's easy as well. In fact, since we're going to pass the results to a function taking one argument, there is a special syntax rule that will let us drop the square brackets, making things look quite a bit neater.
It's also easier than you're making it to initialize the dict in the first place; idiomatic Python code rarely actually needs the word dict.
Putting it all together:
kalg = {'a': '50075', 'b': '18099', 'c': '89885'} # etc.
name = input('Name: ')
print(''.join(kalg[letter] for letter in name if name in kalg))
I can only guess, but this could be what you want:
name = input('Name: ')
kalg = {'a':'50075', 'b': '18099', 'c': '89885'}
keylist = [kalg[letter] for letter in name]
print(" ".join(keylist))