Python: Binary number conversion with an extra letter [duplicate] - python

>>> sum(range(49999951,50000000))
2449998775L
Is there any possible way to avoid the L at the end of number?

You are looking at a Python literal representation of the number, which just indicates that it is a python long integer. This is normal. You do not need to worry about that L.
If you need to print such a number, the L will not normally be there.
What happens is that the Python interpreter prints the result of repr() on all return values of expressions, unless they return None, to show you what the expression did. Use print if you want to see the string result instead:
>>> sum(range(49999951,50000000))
2449998775L
>>> print sum(range(49999951,50000000))
2449998775

The L is just for you. (So you know its a long) And it is nothing to worry about.
>>> a = sum(range(49999951,50000000))
>>> a
2449998775L
>>> print a
2449998775
As you can see, the printed value (actual value) does not have the L it is only the repr (representation) that displays the L
Consult this post

Related

Printing a list as variable values

How would I print a list of strings as their individual variable values?
For example, take this code:
a=1
b=2
c=3
text="abc"
splittext = text.split(text)
print(splittext)
How would I get this to output 123?
You could do this using eval, but it is very dangerous:
>>> ''.join(map(lambda x : str(eval(x)),Text))
'123'
eval (perhaps they better rename it to evil, no hard feelings, simply use it as a warning) evaluates a string as if you would have coded it there yourself. So eval('a') will fetch the value of a. The problem is that a hacker could perhaps find some trick to inject arbitrary code using this, and thus hack your server, program, etc. Furthermore by accident it can perhaps change the state of your program. So a piece of advice is "Do not use it, unless you have absolutely no other choice" (which is not the case here).
Or a less dangerous variant:
>>> ''.join(map(lambda x : str(globals()[x]),Text))
'123'
in case these are global variables (you can use locals() for local variables).
This is ugly and dangerous, because you do not know in advance what a, b and c are, neither do you have much control on what part of the program can set these variables. So it can perhaps allow code injection. As is advertised in the comments on your question, you better use a dictionary for that.
Dictionary approach
A better way to do this is using a dictionary (as #Ignacio Vazquez-Abrams was saying):
>>> dic = {'a':1,'b': 2,'c':3}
>>> ''.join(map(lambda x : str(dic[x]),Text))
'123'
List instead of string
In the above we converted the content to a string using str in the lambda-expression and used ''.join to concatenate these strings. If you are however interested in an array of "results", you can drop these constructs. For instance:
>>> map(lambda x : dic[x],Text)
[1, 2, 3]
The same works for all the above examples.
EDIT
For some reason, I later catched the fact that you want to print the valuesm, this can easily be achieved using list comprehension:
for x in Text :
print dic[x]
again you can use the same technique for the above cases.
In case you want to print out the value of the variables named in the string you can use locals (or globals, depending on what/where you want them)
>>> a=1
>>> b=2
>>> c=3
>>> s='abc'
>>> for v in s:
... print(locals()[v])
...
1
2
3
or, if you use separators in the string
>>> s='a,b,c'
>>> for v in s.split(','):
... print(locals()[v])
...
1
2
3

What does `{...}` mean in the print output of a python variable?

Someone posted this interesting formulation, and I tried it out in a Python 3 console:
>>> (a, b) = a[b] = {}, 5
>>> a
{5: ({...}, 5)}
While there is a lot to unpack here, what I don't understand (and the semantics of interesting character formulations seems particularly hard to search for) is what the {...} means in this context? Changing the above a bit:
>>> (a, b) = a[b] = {'x':1}, 5
>>> a
{5: ({...}, 5), 'x': 1}
It is this second output that really baffles me: I would have expected the {...} to have been altered, but my nearest guess is that the , 5 implies a tuple where the first element is somehow undefined? And that is what the {...} means? If so, this is a new category of type for me in Python, and I'd like to have a name for it so I can learn more.
It's an indication that the dict recurses, i.e. contains itself. A much simpler example:
>>> a = []
>>> a.append(a)
>>> a
[[...]]
This is a list whose only element is itself. Obviously the repr can't be printed literally, or it would be infinitely long; instead, the builtin types notice when this has happened and use ... to indicate self-containment.
So it's not a special type of value, just the normal English use of "..." to mean "something was omitted here", plus braces to indicate the omitted part is a dict. You may also see it with brackets for a list, as shown above, or occasionally with parentheses for a tuple:
>>> b = [],
>>> b[0].append(b)
>>> b
([(...)],)
Python 3 provides some tools so you can do this with your own objects, in the form of reprlib.

Counting occurence within a string Python

I am writing a code to count the occurrences of each letter within a string. I understand that it has been asked and answered Count occurrence of a character in a string, however I cannot figure out why it will not count when I use it.
def percentLetters(string):
string = 'A','B'
print string.count('A')
print string.count('B')
If I was to input percentLetters('AABB'), I would anticipate receiving A=2 and B=2 but am having no such luck. I tried using an if statement earlier however it would not print anything at all
def percentLetters(string):
string='A','B'
if 'A':
print string.count('A')
if 'B':
print string.count('B')
This doesn't work either. Anyone who might have some insight it would be helpful
Don't reassign string inside the function and better to not use string as a variable name at all.
def percentLetters(s):
print s.count('A')
print s.count('B')
percentLetters('AABB')
2
2
string = 'A','B' means you set the string variable to a tuple containing just ("A","B"), it is not pointing to the string you pass in.
In [19]: string = 'A','B'
In [20]: string
Out[20]: ('A', 'B')
Because count is a method/module (whatever it's called in python) for string, the way you do it,
myString ='A','B'
myString is a tuple, not a string.
first, here is the correct version of your code:
def percentLetters(string):
print string.count('A')
print string.count('B')
second, you don't use two strings in an assignment to one variable unless you want to make it a string tuple.

How to reassign a string after removing parts of it by index

I have a string
s = 'texttexttextblahblah",".'
and I want to cut of some of the rightmost characters by indexing and assign it to s so that s will be equal to texttexttextblahblah".
I've looked around and found how to print by indexing, but not how to reassign that actual variable to be trimmed.
Just reassign what you printed to the variable.
>>> s = 'texttexttextblahblah",".'
>>> s = s[:-3]
>>> s
'texttexttextblahblah"'
>>>
Unless you know exactly how many text and blah's you'll have, use .find() as Brent suggested (or .index(x), which is like find, except complains when it doesn't find x).
If you want that trailing ", just add one to the value it kicks out. (or just find the value you actually want to split at, ,)
s = s[:s.find('"') + 1]
If you need something that works like a string, but is mutable you can use a bytearray:
>>> s = bytearray('texttexttextblahblah",".')
>>> s[20:] = ''
>>> print s
texttexttextblahblah
bytearray has all the usual string methods.
Strings are immutable so you can't really change the string in-place. You'll need to slice out the part you want and then reassign it back over the original variable.
Is something like this what you wanted? (note I left out storing the index in a variable because I'm not sure how you're using this):
>>> s = 'texttexttextblahblah",".'
>>> s.index('"')
20
>>> s = s[:20]
>>> s
'texttexttextblahblah'
I myself prefer to do it without indexing: (My favorite partition was commented as winner in speed and clearness in comments so I updated the original code)
s = 'texttexttextblahblah",".'
s,_,_ = s.partition(',')
print s
Result
texttexttextblahblah"

how to create a string which can be used as an array in python?

i want to create a string S , which can be used as an array , as in each element can be used separately by accesing them as an array.
That's how Python strings already work:
>>> a = "abcd"
>>> a[0]
'a'
>>> a[2]
'c'
But keep in mind that this is read only access.
You can convert a string to a list of characters by using list, and to go the other way use join:
>>> s = 'Hello, world!'
>>> l = list(s)
>>> l[7] = 'f'
>>> ''.join(l)
'Hello, forld!'
I am a bit surprised that no one seems to have written a popular "MutableString" wrapper class for Python. I would think that you'd want to have it store the string as a list, returning it via ''.join() and implement a suite of methods including those for strings (startswith, endswith, isalpha and all its ilk and so one) and those for lists.
For simple operations just operating on the list and using ''.join() as necessary is fine. However, for something something like: 'foobar'.replace('oba', 'amca') when you're working with a list representation gets to be ugly. (that=list(''.join(that).replace(something, it)) ... or something like that). The constant marshaling between list and string representations is visually distracting.

Categories