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
Related
This question already has answers here:
python is operator behaviour with string [duplicate]
(1 answer)
Python: Why operator "is" and "==" are sometimes interchangeable for strings? [duplicate]
(3 answers)
Closed 2 years ago.
Please do not mark duplicated YET.
I did read this Python is vs ==
I have read around and noticed == vs is that is checks if same memory location and == is used to compare two values but recently I was using is by accident BUT to me it's acting weird and I am don't really understand why though.
I am trying to parse a url path to see if the page number matches for example
a = '9'
b = '/category-1-11-9.html'
c = b.split('.html')[0].split('-')[-1]
print(a is c, ' bool') # this gives True
a = '10'
b = '/category-1-11-10.html'
c = b.split('.html')[0].split('-')[-1]
print(a is c, ' bool') # this gives False
I figured if the number is a single digit, I get True as return and if number is 10 or more I get False
I tried to print both a and c to see their type and value, ended up both typeandvalue` are the same. But why with a single digit it gives True and double digits it gives False?
I am quite confused with this even after reading articles about is
Using python version 3.7.7
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 ('').
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:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 5 years ago.
I know there are a few ways to remove vowels, but when I try the method below, the output I get is the string just being printed len(string) times. For example:
s="Labido Labidi"
for i in s:
if i.lower()=='a' or 'e' or 'i' or 'o' or 'u':
s=s.replace(i,"")
print(s)
The resultant output is:
Labido Labidi
Labido Labidi
...and so on
What's going on inside the loop ? It isn't even going through the if statement.
You are using the or statement incorrectly:
s="Labido Labidi"
for i in s:
if i.lower()=='a' or i.lower()=='e' or i.lower()=='i' or i.lower()=='o' or i.lower()=='u':
s=s.replace(i,"")
print(s)
You need to put your full evaluational statement after the or
The problem is your if logic.
After the first or you have to repeat i.lower() == 'e', etc.
Try this:
s="Labido Labidi"
for i in s:
if i.lower() in 'aeiou':
s=s.replace(i,"")
print(s)
The problem is your if condition. or connects two boolean expressions; it doesn't work the same as in English. What you need to check is
if i.lower()=='a' or
i.lower()=='e' or
...
Better yet, just make a single check on a list of vowels this way:
if lower() in "aeiou":
DETAILS
Any expression used as a Boolean value is evaluated according to whether it is "truthy" or "falsey". Non-Boolean data types are sometimes not obvious. In general, zero and `None` values are "falsey", and everything else is "truthy".
Thus, each of the single letters is "truthy", so the Python interpreter regards your if statement as if it says
if i.lower()=='a' or True or True or True or True:
In short, this is always True; your program thinks that everything is a vowel.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
have just started learning python and this question came up to my mind
is there a shorter way to determine if a string equals 'something' or 'somethingelse'?
example:
input = raw_input("question?")
while input != 'n' and input != 'y':
#ask question again
You could check whether it is in a list or set.
input = raw_input("question?")
while input not in ['n', 'N']:
#ask question again
If you are just trying to accept two cases though, you could also just call lower on the input.
while input.lower() != 'n':
#ask question again
Perhaps unexpectedly, 'a' != input != 'b' works. It resolves the same way as ('a' != input) and ('b' != input). You can do the same thing with ==, or with <, >, etc. on numbers, as well.
Oh, but you have to be careful if you chain it longer than three things, or use multiple different comparison operators.
If it's a case issue, then you can:
while input.lower() != 'n'