The question on my assignment is as follows:
Write a function that takes, as an argument, a string, identified by the variable aString. If the string only contains digits 0 and 1, return the string formed by concatenating the argument with the string "is a binary string." Otherwise, return a string indicating the length of the argument, as specified in the examples that follow. Name this function AmIBinary(aString).
I am having trouble figuring out how to form a loop which searches through a string and determines whether or not the string is a binary string. I understand how to get the length of a string, I just don't understand how to figure out if it is a binary string.
Try this !
import re
def AmIBinary(aString):
#test_str='Vijay'
if re.match("[01]+",aString):
print('Binary string')
else:
print(len(test_str))
#AmIBinary("Vijay")
AmIBinary('010101')
You can use a for loop through a string the same way you can use with a list of numbers.
For example:
numbers = [1, 2, 3, 4]
You can use:
for number in numbers:
# Do something
In your case, you just need to switch the number list by the string you receive as an argument like this:
aString = '100100100'
for number in aString:
# Check if there's a different number than '0' and '1'
Look that in this case you need to compare it with the string version of the number, because you're iterating a string, so each value you receive from the for loop will be a string too.
In the end, you'll probably have something like this:
def AmIBinary(aString):
for number in aString:
if number != '0' and number != '1':
return len(aString)
aString += 'is a binary string'
return aString
As you can see I am iterating through the string to check if any element of it is different than '1' and '0', if it is, I just return the length of the string, otherwise, if I checked every value in the string and everything is fine, I concatenate 'is a binary string' to the original string and return it.
I hope this helps.
Try the build-in function remix without use loop.
def AmIBin(s):
try:
if s.startswith('0b'):
int(s, 2)
else:
int('0b{}'.format(s), 2)
except:
return False
else:
return True
A binary string has been defined as a string that only contains "0" or "1". So, how about checking each 'character' in the string, and if it's not a "0" or "1" you will know that the string is not a binary string.
Related
Writing a program:
Input string from the user
print out whether this string is a palindrome or not
Also, I found a few other codes online but want to work with this code only.m Please let me know the error
i = str(input())
for item in i:
print(item)
if int(i[item]) == int(i[-item]):
print('yes')
else:
print('no')
Use a String slice (The i[::-1] will reverse the string):
i = input()
if i == i[::-1]:
print("Yes")
else:
print("No")
This will take the input from the user and compare it against the same input in reverse.
try this:
word="TOT"
i=word[::-1]
if i==word:
print("palandrom")
Although for item in i: loops through every character in the string, there are several problems with your code line if int(i[item]) == int(i[-item]):. First of all, item is going to be a character from your string. So if the user types "hello", then i[item] first looks for i['h']. Since 'h' is a character and not a number, this makes Python think that i is a dictionary and not a string, and thus tells Python to look for a dictionary named i and return the value where the key is h. That won't work since i is your original string, not a dictionary.
It looks like what you meant to do here is compare i[0] (the first character in the string) to i[-1] (the last character in the string), then i[1] to i[-2], and so on. But even you if looped through the position numbers, i[-item] doesn't mathematically give you what you want.
Yet another issue here is that you're checking each character one at a time and returning "yes" or "no". What you ultimately want though is to output one simple answer: whether your string is a palindrome or not.
Also, there's no need to put str() around input(), since input returns a string anyway, even if the user enters only numerals. By the way, even though you're using i as your string variable, the usual convention in programming is to use i to denote some sort of integer, such as one you're iterating through in a for loop. But that's OK for now.
As some of the other answers have shown, i[::-1] is a quick way to return the reverse of a string itself. So if you're OK with seeing the output return True if the string is a palindrome and False if it isn't, then here's an extremely simple way to do it:
i = input()
print(i == i[::-1])
If the string i is identical to itself reversed, then i == i[::-1] returns True. If not, it returns False. The print statement then prints whichever the answer is.
However, if you really do want to do it the long way, testing character by character in a loop, then here's one way to do it. You could make a function that takes in a string and does the work:
def is_palindrome(mystring):
# The "//2" here divides by 2 and ignores the remainder. So if
# there are an even number of letters, we'll test each pair. If
# It's an odd number, then we don't care about the middle character
# anyway. Compare [0] to [-1], then [1] to [-2], [2] to [-3], and so on.
for position in range(0, len(mystring)//2):
# If we've found a mismatched pair of letters, then we can
# stop looking; we know it's not a palindrome.
if mystring[position] != mystring[(-1 * position) - 1]:
print("This is NOT a palindrome")
return # This breaks you out of the entire function.
# If we've gotten this far, then the word must be a palindrome.
print("This is a palindrome")
# Here's where we run the command to input the string, and run the function
mystring = input("Enter your string: ")
is_palindrome(mystring)
I am brand new to python and have searched the site on this, but still can't figure it out. It's for a homework assignment, so not looking for the answer, but I can't figure out what I'm doing wrong and getting a syntax error (I'm stuck on the first rule...)
The assignment:
We will assume that the credit card number is a string consisting of 14 characters and is in the format ####-####-####, including the dashes, where ‘#’ represents a digit between 0-9, so that there are 12 digits overall.
1. The first digit must be a 4.
2. The fourth digit must be one greater than the fifth digit; keep in mind that these are separated by a dash since the format is ####-####-####.
3. The sum of all digits must be evenly divisible by 4.
4. If you treat the first two digits as a two-digit number, and the seventh and eighth digits as a two-digit number, their sum must be 100.
Here is my code so far. I've read that you can't compare characters to numbers, but nothing I've tried has worked. Any help/guidance would be appreciated!
def verify(number) :
if input ['0'] == '4'
return True
if input ['0'] != '4'
return "violates rule #1"
input = "4000-0000-0000" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output of the function
your code is fine, but there are a couple of issues
def verify(number) :
if input [0] == '4':
return True
if input [0] != '4':
return "violates rule #1"
input = "4000-0000-0000" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output of the function
first of all, indentation matters in python, everything that belongs in your function definition should be indented.
second, if statements should be followed by :. that is all
Your code is incorrect:
def verify(number):
# incorrect indent here
if input ['0'] == '4' # missing : and undeclared input variable, index should be int
return True
if input ['0'] != '4' # missing : and undeclared input variable, index should be int
return "violates rule #1"
Fixed code:
def verify(number):
if number[0] != '4'
return "violates rule #1"
# other checks here
return True
Also I recommend to return False from this function instead of error string. If you want to return string with error, consider using tuple like (is_successful, error) or custom object.
Have a look at string indexing:
Strings can be indexed (subscripted), with the first character having
index 0. There is no separate character type; a character is simply a
string of size one:
>>> word = 'Python'
>>> word[0] # character in position 0 'P'
>>> word[5] # character in position 5 'n'
Then read about if-statements - your code is missing the :, and the second if can be replaced by an else clause.
You may also want to check the argument of the function, not the global variable input (this is a bad name, since it shadows the input() built-in)
Suggested fix:
def verify(number) :
if number[0] == '4':
return True
else:
return "violates rule #1"
testinput = "4000-0000-0000" # change this as you test your function
output = verify(testinput) # invoke the method using a test input
print(output) # prints the output of the function
I'm practicing coding on codingbat.com since I'm a complete beginner in python, and here is one of the exercises:
Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
Here is my attempt at defining the function string_bits(str):
def string_bits(str):
char = 0
first = str[char]
for char in range(len(str)):
char += 2
every_other = str[char]
return (first + every_other)
Running the code gives an error. What's wrong with my code?
A different approach, with an explanation:
If you need to handle a sentence, where spaces would be included, you can do this using slicing. On a string slicing works as:
[start_of_string:end_of_string:jump_this_many_char_in_string]
So, you want to jump only every second letter, so you do:
[::2]
The first two are empty, because you just want to step every second character.
So, you can do this in one line, like this:
>>> " ".join(i[::2] for i in "Hello World".split())
'Hlo Wrd'
What just happened above, is we take our string, use split to make it a list. The split by default will split on a space, so we will have:
["Hello", "World"]
Then, what we will do from there, is using a comprehension, iterate through each item of the list, which will give us a word at a time, and from there we will perform the desired string manipulation per i[::2].
The comprehension is: (documentation)
i[::2] for i in "Hello World".split()
Finally, we call "".join (doc), which will now change our list back to a string, to finally give us the output:
"Hlo Wrd"
Check out the slicing section from the docs: https://docs.python.org/3/tutorial/introduction.html
The problem is that the char += 2 returns a value greater than len(str) as len(str)-1 (the range) + 2 is longer than the string. You could do:
def string_bits(string):
if len(string) == 2:
return string[0]
result = ''
for char in range(0,len(string),2):#range created value sin increments of two
result += string[char]
return result
A more succinct method would be:
def string_bits(string):
return string[::2]
You should avoid using 'str' as a variable name as it is a reserved word by Python.
Ok, for me:
You should not use str as a variable name as it is a python built-in function (replace str by my_str for example)
For example, 'Hello' length is 5, so 0 <= index <= 4. Here you are trying to access index 3+2=5 (when char = 3) in your for loop.
You can achieve what you want with the following code:
def string_bits(my_str):
result = ""
for char in range(0, len(my_str), 2):
result += my_str[char]
return result
The error you are getting means that you are trying to get the nth letter of a string that has less than n characters.
As another suggestion, strings are Sequence-types in Python, which means they have a lot of built-in functionalities for doing exactly what you're trying to do here. See Built-in Types - Python for more information, but know that sequence types support slicing - that is, selection of elements from the sequence.
So, you could slice your string like this:
def string_bits(input_string):
return input_string[::2]
Meaning "take my input_string from the start (:) to the end (:) and select every second (2) element"
How can I replace even and odd-indexed letters in my strings? I'd like to replace odd-indexed characters with uppercased letters and even-indexed characters with lowercased ones.
x=input("Enter String: ")
How can I modify the inputted string?
This sounds a little like a "do my homework for me" post, but I'll help you out, as I need the training myself.
You can do this by breaking down the problem. (As I am quite new with python syntax, I'm gonna assume that the user has already given an input to string x)
Make a loop, or otherwise iterate through the characters of your string
Make sure you have an index number for each character, which increments for each one
Check if the number is even, by using modulus of 2 (%2). This returns the remainder of a number when divided by 2. In the case of even numbers, that will be 0.
If %2 == 0 set letter to lower case, else set letter to upper case.
append letter to new String, which you defined before the loop. You cannot directly alter a single character in a String, because they are immutable. This means that you cannot change the String itself, but you can assign a new String to the variable.
Done. Print and see if it worked.
Code:
x = "seMi Long StRing WiTH COMPLetely RaNDOM CasINg"
result_string = ""
index = 0;
for c in x:
if(index%2 == 0):
result_string += c.lower()
else:
result_string += c.upper()
index+=1
print(result_string)
s=input()
l=[]
s=s.lower()
l=[i.upper() if s.index(i)%2==0 else i for i in s ]
print("".join(l))
x = 'myname'
for item in range(len(x)):
if item%2==0:
print(x[item].upper())
else:
print(x[item].lower())
this is the for loop i was referring to. but the thing with this line of code is that it is specific to the value you have assigned to the variable x where as the function i provided above can take any string value without us having to repeat the code each time.
def myfunc(string):
result=''
for x in range(len(string)):
if x%2==0:
result=result+string[x].upper()
else:
result=result+string[x].lower()
return result
The above is a function for the question you asked.
A non-function for loop might be easier to grasp right now (like you I am very new to Python as well. So for me it was easier to understand the for loop before I got into functions. Look at my next post for the same.
In a function in Django, the user can send me a number or a string, and I want to know if I received a number or a String (Tip: The number will always be an integer between 1-6)
I want to know if it's possible to detect this and how (with an example), as the number or string I'm getting will tell me what to do next.
You can try to convert the string to a number using int(), catching the exception:
def isNum(data):
try:
int(data)
return True
except ValueError:
return False
This returns True only if the string can be converted to an integer number.
What about: if isinstance(data, int):
I'm assuming your number will still be encased in a string, ie. "1" or "4" or "6" - if that's the case, then there are several ways to do it; you could use a regex to check whether it is a number or not, or you could knock up a function that would look something like this
def isNumber(your_input_string):
return len(your_input_string) == 1 and your_input_string in "123456"
Since the number will always be between 1 and 6, it can only be a string of length 1, and it must be contained in the string '123456', since... well, those are the allowed numbers.
EDIT:
As pointed by Martijn Pieters in the comments below, that is a roundabout way of doing it; an easier solution would be just to check whether the string is between '1' or '6'.
def isNumber(your_input_string):
return len(your_input_string) == 1 and '1' <= your_input_string <= '6'