This question already has answers here:
Why are str.count('') and len(str) giving different output?
(3 answers)
How does the count() method work? [duplicate]
(1 answer)
Closed 4 years ago.
This is a short one, yet very irritating. I know I can count the amount of times a string occurs within another string like this:
'banana'.count('a')
>>>3
meaning that banana contains the letter "a" 3 times.
This is where it gets kind of weird.
My first confusion is - when I do 'foo'.count(''), what does Python look for?
is '' == None == anything?
It doesn't seem to be the case, but then again, what IS '' logically speaking? And more importantly, why does
'test'.count('')
>>>5
return one more than the length of the string?
What the hell is included in a string that's always 1 higher than the amount of letters? the void?
EDIT: the ' character twice looks like one " character. I am talking about two times ' here, to avoid confusion
EDIT2: There seems to be some confusion about how the amount of '' happen. Refer to comments below.
Every string1 can be thought of as:
any_string = "" + "".join(any_string) + ""
which contains exactly len(any_string) + 1 instances of ''.
For "foo" for example, it would be:
"" + "f" + "" + "o" + "" + "o"+ ""
# |----- from join -------|
As it can be seen there are 4 instances of "" in it.
Note however, that this is a problem where no answer or all answers could somehow support a case for themselves. It get's philosophical:
How much nothing is contained in nothing?
How much nothing is contained in something?
This answer tries to explain the convention used by Python and does not intend to suggest that this is the way all languages do it \ should be doing it; it is just how Python does it.
1Empty strings are an exception and are handled differently; they simply return 1; which is yet another convention.
str.count(sub)
Counts the number of occurrences of sub in str.
Since strings are sequences, it basically counts the number of splits sub would cause in str.
An empty string is at the beginning, between each character, and at the end.
Hence, why when you use 'test', which has a len of 4, you get 5 occurrences of sub ('').
Related
This question already has answers here:
Check if a string contains a number
(20 answers)
Closed 2 years ago.
I have a working function that takes an input as string and returns a string. However, I want my function to return an empty string ("") if the input contains any number in whatever position in the string.
For example :
>>> function("hello")
works fine
>>> function("hello1")
should return ""
The main thing you need for that is the method "isdigit()" that returns True if the character is a digit.
For example:
yourstring="hel4lo3"
for char in yourstring:
if char.isdigit():
print(char)
Will output 4 and 3.
I think it is a good exercise for you trying to do your code from that!
This question already has answers here:
Understanding slicing
(38 answers)
Closed 4 years ago.
I don't know what 'Count : Count' does in my code. Below is the function that this is used in on line 4
I tried printing it but it gave me an error. CommandList is a string variable as well as Command.
def GetPositionOfCommand(CommandList, Command):
Position = Count = 0
while Count <= len(CommandList) - len(Command):
if CommandList[Count:Count + len(Command)] == Command:
return Position
elif CommandList[Count] == ",":
Position += 1
Count += 1
return Position
Position = GetPositionOfCommand(Items[IndexOfItem].Commands, "get")
Your question is off, since Count: Count does nothing in the code you show. Rather, what acts is Count:Count + len(Command). That would be better written as Count: (Count+len(Command)).
Both CommandList and Command are strings or lists or similar data types (I'll say strings hereafter), while Count is an integer. In particular, Count is an index into CommandList.
The expression CommandList[Count:Count + len(Command)] is a slice of CommandList. In other words, that expression is a sub-string of the string CommandList. That sub-string begins at the index position held in Count and stops just before the index position Count + len(Command). That sub-string has the same length that the string Command has.
Therefore the entire line
if CommandList[Count:Count + len(Command)] == Command:
checks if the sub-string pointed to by variable Count is equal to the string Command. If the sub-string and the string are equal, the next line executes, namely the return statement.
Is that clear? Read up more on Python's slices--the link I gave you is a good start. Slices are just one reason Python handles lists and strings so much better than most other languages. The code is written a little confusingly, so it looks like Count:Count is an expression in itself. The code should have used different spacing and perhaps parentheses to show that the inner expression is Count + len(Command) and the colon is used after that. Order of operations shows itself again!
This question already has answers here:
String count with overlapping occurrences [closed]
(25 answers)
Closed 4 years ago.
im just learning how to program on edx, and theres this question that i just can seem to understand not to even talk of solving. please i need solutions and idea on how to understand the question and implement it
QUESTION-
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2
Since you are just learning, start with basic method.
Simplest apporch will be start from the begining consider all the substrings of the length of the substring that is needed to be counted. If there is a match increase the count.
You can refer the following code to get an idea.
s = 'azcbobobegghakl'
sb = 'bob'
results = 0
sub_len = len(sb)
for i in range(len(s)):
if s[i:i+sub_len] == sb:
results += 1
print(results)
This question already has answers here:
Python replace function [replace once]
(6 answers)
Replace 2 characters within a reversed string at once
(2 answers)
Closed 4 years ago.
I'm playing around with a simple crypting program, and I want it to work so that every specific symbol, always will turn into another specific symbol. That might not be the best description, but I don't know how else to put it... For an example:
"a" is going to be "h"
"A" is going to be "k"
"h" is going to be "W"
text_1 = "aAh"
text_2 = text_1.replace('a', 'h')
text_3 = text_2.replace('A', 'K')
text_4 = text_3.replace('h', 'W')
print text_4
#the output is "WKW"
#I need the output to be "hKW"
The problem is, that I'm using the replace-command for every single symbol-replacement, so if we suppose that the codes are typed in the same order as our example, and the message I want to crypt is "aAh", then I would like the crypted output to be "hKW" but actually we get this output instead "WKW".
I know why this is happening, so my question is:
How do I get the program to crypt the message the way I intended it to do?
The problem you have is that you're applying your changes to intermediate strings (so the previous changes will affect the result)
Consider trying to calculate the intended changes on the initial string for each character and build the final string after.
You can use a dict for your character mapping and then use a generator expression to translate the characters:
m = {'a': 'h', 'A': 'K', 'h': 'W'}
print(''.join(m.get(c, c) for c in text_1))
This outputs:
hKW
This question already has answers here:
invalid syntax on =? [closed]
(2 answers)
Closed 8 years ago.
This is in python and I'm having a little trouble finding this out, I put.
s = 'goodbye'
and I want to know if the first letter is a g.
so i put
s[0] = 'g'
but i get an error, what is the right way to finding this?
A single = means 'assignment', and doing two == means 'compare and see if they're equal'. The difference between the two can be subtle (just a single character difference!), so make sure you don't get confused between the two
You want s[0] == 'g':
if s[0] == 'g':
print "word starts with 'g'"
Doing s[0] = 'g' is telling Python "change the first letter of the string to 'g'". However, that fails because in Python, strings are immutable -- they can never be changed.
You could use the startswith(prefix) method (returns True if string starts with the prefix, otherwise returns False):
>>> s = 'hello'
>>> a = s.startswith('h')
>>> a
True