Beginner Question why can I do str(number) and not str(letter) - python-3.x

As the title says, I dont understand why letters without quotes doesn't convert into a string while using the str() method.
f = str(ab)
print(type(ab))
print(type(f))
returns a NameError: name 'ab' is not defined.
So I have to write it as 'ab'.
When using numbers, I do not need the quotes, like
f = str(10)
print(type(10))
print(type(f))
returns
<class 'int'>
<class 'str'>
Is it because letters doesnt belong to a class?

Because variables are any combination of letters/numbers and symbols, such as Hello_There. Therefore as far as Python is concerned ab is a variable name, not a string. To tell Python its a string you have to put quote marks around it.

Related

Difference between `print(9)` and `print(str(9))`

What is the difference between print(9) and print(str(9)) in Python when the output is the same for both functions?
print will always first try to call __str__ on the object you give it. In the first case the __str__ of the int instance 9 is '9'.
In the second case, you first explicitly call str on 9 (which calls its __str__ and yields '9'). Then, print calls '9''s __str__ which, if supplied with a string instance, returns it as it is resulting in '9' again.
So in both cases, in the end print will print out similar output.
From the documentation:
All non-keyword arguments are converted to strings like str() does
print(str(9))
print(9)
Output:
9
9
There is no change in output. But if we check the data type by executing,
print(type(str(9)))
print(type(9))
Then we get output as,
<class 'str'>
<class 'int'>
So, you can see, the types are different but the output is same.
In simple terms:
An integer is a variable that specifically holds a numerical value. Whereas a string is a variable that can hold a range of characters (including numbers).
print(9) says it should print the NUMERICAL value 9
print(str(9)) says it should print the character 9,
So if you were to do additions on both types for instance:
9 + 9 will always return 18
str(9) + str(9) will always return 99

Python how to remove the first set of a character in a string?

My variable x has a value of "000032403" and I want to remove the first set of zeros but I want to keep the other! How I gonna do that?
Note: Please give me any suggestions without knowing the amount of zeros in the beginning, because in my program this value is obtained from the user.
You can use the lstrip() function of the string class like this
>>> x = "000032403"
>>> x.lstrip("0")
"32403"
This will "return a copy of the string with leading characters removed".
Here's a link to the docs

Python: numerical elements in a list cant be converted into integers

Hello people,
I've got a problem with my code. For some reason the values are not converted to integers from strings and are not adding up. Here is my code.
def SumOfState(i,j):
cf=readPopest(file1)
sum2=[]
sum7=[]
Diff=0
for y in range((j)):
StateList=str(cf[y+i]).split(',')
sum2.append(StateList[2])
sum7.append(StateList[7])
results2 = [int(i) for i in sum2]
results7 = [int(i) for i in sum7]
print sum(results2)
print sum(results7)
Error message : Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
cf=readPopest(file1)
the code ^^ gives a list containing words and numbers. One element is taken % split into sublists.
Ive tried the int() function and the for loop variant of it.
suggest me an edit, please.
Really appreciate any help.
Thanks.
-Addie Vanhala
I guess looking at you code, it is because sum2 and sum7 contain non integers, probably because some part of file1 (accessed though readPopest) is non int.

Convering double backslash to single backslash in Python 3

I have a string like so:
>>> t
'\\u0048\\u0065\\u006c\\u006c\\u006f\\u0020\\u20ac\\u0020\\u00b0'
That I made using a function that converts unicode to the representative Python escape sequences. Then, when I want to convert it back, I can't get rid of the double backslash so that it is interpreted as unicode again. How can this be done?
>>> t = unicode_encode("
>>> t
'\\u0048\\u0065\\u006c\\u006c\\u006f\\u0020\\u20ac\\u0020\\u00b0'
>>> print(t)
\u0048\u0065\u006c\u006c\u006f\u0020\u20ac\u0020\u00b0
>>> t.replace('\\','X')
'Xu0048Xu0065Xu006cXu006cXu006fXu0020Xu20acXu0020Xu00b0'
>>> t.replace('\\', '\\')
'\\u0048\\u0065\\u006c\\u006c\\u006f\\u0020\\u20ac\\u0020\\u00b0'
Of course, I can't do this, either:
>>> t.replace('\\', '\')
File "<ipython-input-155-b46c447d6c3d>", line 1
t.replace('\\', '\')
^
SyntaxError: EOL while scanning string literal
Not sure if this is appropriate for your situation, but you could try using unicode_escape:
>>> t
'\\u0048\\u0065\\u006c\\u006c\\u006f\\u0020\\u20ac\\u0020\\u00b0'
>>> type(t)
<class 'str'>
>>> enc_t = t.encode('utf_8')
>>> enc_t
b'\\u0048\\u0065\\u006c\\u006c\\u006f\\u0020\\u20ac\\u0020\\u00b0'
>>> type(enc_t)
<class 'bytes'>
>>> dec_t = enc_t.decode('unicode_escape')
>>> type(dec_t)
<class 'str'>
>>> dec_t
'Hello € °'
Or in abbreviated form:
>>> t.encode('utf_8').decode('unicode_escape')
'Hello € °'
You take your string and encode it using UTF-8, and then decode it using unicode_escape.
Since a backslash is an escape character and you are searching for two backslashes you need to replace four backslashes with two - i.e.:
t.replace("\\\\", "\\")
This will replace every r"\\" with r"\". The r indicates raw string. So, for example, if you type print(r"\\") into idle or any python script (or print r"\\" in Python 2) you will get \\\\. This means that every "\\" is really just a r"\".
user1632861 suggested that you use .replace("\\", ""), but this replaces ever r"\" with nothing. Try the above method instead. :D
In this case, however, it appears as though you are reading/receiving data, and you probably want to use the correct encoding and then decode to unicode (as the person above me suggested).
You only got one backslash in your code, but backslashes are represent as \\. As you can see, when you use print(), there's only one backslash. So if you want to get rid of one of the two backslashes, don't do anything, it's not there. If you wanna get rid of both, just remove one. Again use \\ to represent one backslash: t.replace("\\", "")
So your string never has two backslashes in the first place, it shouldn't be the problem.

Defining a function name that starts with a number (in Python 3)?

I have tried creating the following function:
def 3utr():
do_something().
However, I get a SyntaxError. Replacing the "3" by "three" fixes the problem.
My questions are:
Why is it a syntax error?
Is there a way to have a function name start with a number in Python 3?
It is a syntax error because the language specification does not allow identifiers to start with a digit. So it’s not possible to have function names (which are identifiers) that start with digits in Python.
identifier ::= (letter|"_") (letter | digit | "_")*
Python 2 Language Reference
Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z, the underscore _ and, except for the first character, the digits 0 through 9.
Python 3 Language Reference
One workaround is use Roman numerals:
>>> def xxiv():
... print("ok\n")
...
>>> xxiv()
ok
If you really want to be distinctive.
You can add '_' in front of an identifier
For instance
def _3utr():
Then call the function
_3utr()

Resources