This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 7 years ago.
When I do the following:
def encrypt(string):
str(string).replace('0', 'A')
return(string)
encrypt(000)
Only 0 comes out as the output.
What I want to do is replace all 0s with an A to test an encryption program I am going to make. The output I want is AAA.
So why doesn't it work when I try to replace 0 with A?
Python strings are immutable. No method or operator therefore is able to mutate the string in-place as you appear to desire.
Rather, they return a result that you must assign to a name (or return, whatever).
So, use:
return str(string).replace('0', 'A')
BTW, immutable strings are such a great idea that Java and many later languages copied them from Python...:-)
Of course, if you use 000 with NO quotes as the argument, the function has and can have no idea how many zeros you typed -- it just receives the number 0! You'd better pass a string (quotes around it), so probably lose the str here, too.
you need to assign the change to the string.
def encrypt(string):
return str(string).replace('0', 'A')
You will not be able to get 'AAA' out if you pass the NUMBER 000. Because the number 000 is the same as 0 and gets converted to the string '0'. If you properly implement your return/replace function as described in the other answers the result for inputting the number 000 with return 'A'.
Probably you want a new function that you pass strings not numbers otherwise you will never be able to differentiate between 000 and 0 (or any other number of zeros 000000000000, etc)
BTW, you called your function variable "string" even though you are passing a number and then converting it to a string with str. This is good foreshadowing. Here's a function that will do what you want with strings, not numbers:
def encrypt(string):
return string.replace('0', 'A')
>>> encrypt('000')
'AAA'
There is nothing wrong with your code.
You should pass 000 as string if you don't 000 is treated as 0 so you get only one A replacing single 0.
def encrypt(string):
return str(string).replace('0', 'A')
print encrypt('000')
This gives AAA as output.
Related
This question already has answers here:
How do I split the definition of a long string over multiple lines?
(30 answers)
Closed 9 months ago.
Very new to python here. How do you split a very long dictionary value over two lines while still having it appear as one line when it is output with print()? See code below.
glossary = {'dictionary' : 'A mutable associative array (or dictionary) of key and value pairs. Can contain mixed types (keys and values). Keys must be a hashable type'}
I've tried using triple quotes (i.e. """) with no success since I don't think the value is technically a string.
you can use \ (backslash) to continue code onto the next line
e.g.
print("hello \
how are you")
would return
hello how are you
edit: you should be able to use """ as (from my understanding) it just converts it to a normal string but adds the line breaks. this wouldnt give the result you wanted but it should work
edit: just tested the above:
list = ['hi', '''thing1
thing2''']
print(list)
ouput:
['hi', 'thing1\nthing2']
that \n means newline so i would use the backslash as i mentioned above if you want the correct output
I am writing a small function that turns a integer into its reciprocal in its fraction form. This is how I've defined my function so far:
def reciprocal (number):
return "1/",number
This sort of works but the problem is that it doesn't print the answer on the screen as I'd like to because say i did print reciprocal(3) it would show ('1/', 3) on the screen instead of 1/3. I have tried all sorts of combinations of speech marks and brackets in the code but the answer has still got extra brackets and back-ticks around it. I am using python 2.7.10, is there any way to get rid of these? Or is there any other simple way to express an integer as its reciprocal in fraction form that would get rid of them? Thank you
Yes. Because what this line is actually doing is returning a tuple:
return "1/",number
If you simply print:
type(reciprocal(3))
You will see the result will be tuple.
In order to keep the functionality of:
print(reciprocal(3))
You would want to do something like this instead:
return "1/{}".format(number)
Now, the above will actually return you a string instead of a tuple. The above is using the string format method, which you can read about here. Ultimately what you are doing is creating a string that will look like 1/x, where x will be number. The way to denote the x is by using the curly braces which is then used a placeholder that will set whatever you passed to format. Read more in the documentation to understand how it works.
To help expand it, what it actually looks like when separated is this:
s = "1/"
Now, you want to be able to set your argument number. The string object supports several methods, one of which, is format. So you can actually simply call it: s.format(). However, that won't simply work the way you want it. So, per the documentation, in order to use this format method, you need to set in your string where exactly you want to set your argument that you want to place in your string. This is done by using the placeholder characters {} to indicate this. So:
s = "1/"
Will now be
s = "1/{}".format(number)
We set our {} as the placeholder of where we want number to be, and we assigned what will be in that placeholder by passing number to format.
You can further see how now you have a string if you in fact print the type of the result:
print(type(reciprocal(3)))
You will see it is now a str type.
As a note in Python, you can create a tuple with comma separated values:
>>> d = 1, 2
>>> type(d)
<class 'tuple'>
This is exactly why your function returns the tuple, because of the fact you are returning two values simply separated by a comma.
You can try this:
def reciprocal (number):
return "1/{}".format(number)
print reciprocal(4)
print reciprocal(100)
Output:
1/4
1/100
Right now you're returning a tuple made of the string "1/" and your number because of the comma. I think what you want to do is return just a string.
Something like return "1/" + str(number)
This question already has an answer here:
Check if string in the exact form of "<int1>,<int2>" in Python
(1 answer)
Closed 6 years ago.
I'm converting a string of two integers into a tuple. I need to make sure my string is formatted exactly in the form of:
"<int1>,<int2>"
This is not a duplicate to an earlier question. Since that did not address restrictions I did not know about earlier. My parameter will be "4,5" for example. I'm not allowed to write other helper functions to check if they are formatted correctly. The checks must be done in a single function called convert_to_tuple
I just looked at the project specs again, and I'm not allowed to import any new modules, so regex is off the table. I'm also not allowed to use try/catch either.
Can you point me in the write direction? Thanks
Here is my code for converting the string into a tuple. So I need some type of check for executing this code.
if foo:
s1 = "12,24"
string_li = s1.split(',')
num_li = [int(x) for x in string_li]
num_tuple = tuple(num_li)
return num_tuple
else:
empty_tuple = ()
return empty_tuple
Does this work? (Edited to meet OP's requirements)
def is_int(string):
return string and set(string).issubset(set('1234567890'))
def check_str(s):
parts = s.split(',', 1)
return len(parts) == 2 and is_int(parts[0]) and is_int(parts[1])
I believe for testing (without converting, and without regexes or exception handling) a simple:
vals = s1.split(',')
if len(vals) == 2 and all(map(str.isdigit, vals)):
would verify that there are two components and both of them are non-empty and composed solely of digits.
This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 9 years ago.
I know that in python, you can't simply do this:
number = 1
print "hello number " + number
you have to do this:
print "hello number " + str(number)
otherwise you'll get an error.
My question is then, being python such a compact language and this feature of automatic casting/converting from integer to string available in so many other languages, isn't there away to avoid having to use the str() function everytime? Some obscure import, or simply another way to do it?
Edit: When I say another way, I mean simpler more compact way to write it. So, I wouldn't really consider format and alternative for instance.
Thanks.
You can avoid str():
print 'hello number {}'.format(number)
Anyway,
'abc' + 123
is equivalent to
'abc'.__add__(123)
and the __add__ method of strings accepts only strings.
Just like
123 + 'abc'
is equivalent to
(123).__add__('abc')
and the __add__ method of integers accept only numbers (int/float).
You can use string formatting, old:
print "hello number %s" % number
or new:
print "hello number {}".format(number)
I tend to use the more compact format
>>> print "one",1,"two",2
one 1 two 2
Or, in python 3,
>>> print("one",1,"two",2)
one 1 two 2
Notice however that both options will always introduce a space between each argument, which makes it unsuitable for more complex output formatting, where you should use some of the other solutions presented.
As this answer explains, this will not happen in Python because it is strongly typed. This means that Python will not convert types that you do not explicitly say to convert.
Yes, this is homework.
I have the basic idea. I know that basically I need to introduce a for loop and set if's saying if the value is above 9 then it's a, b, c, and so forth. But what I need is to get the for loop to grab the integer and its index number to calculate and go back and forth and then print out the hex. by the way its an 8 bit binary number and has to come out in two digit hex form.
thanks a lot!!
I'm assuming that you have a string containing the binary data.
In Python, you can iterate over all sorts of things, strings included. It becomes as simple as this:
for char in mystring:
pass
And replace pass with your suite (a term meaning a "block" of code). At this point, char will be a single-character string. Nice an straight forward.
For getting the character ordinal, investigate ord (find help for it yourself, it's not hard and it's good practice).
For converting the number to hex, you could use % string formatting with '%x', which will produce a value like '9f', or you could use the hex function, which will produce a value like '0x9f'; there are other ways, too.
If you can't figure any thing out, ask; but try to work it out first. It's your homework. :-)
So assuming that you've got the binary number in a string, you will want to have an index variable that gets incremented with each iteration of the for loop. I'm not going to give you the exact code, but consider this:
Python's for loop is designed to set the index variable (for index in list) to each value of a list of values.
You can use the range function to generate a list of numbers (say, from 0 to 7).
You can get the character at a given index in a string by using e.g. binary[index].