This question already has answers here:
How to use digit separators for Python integer literals?
(4 answers)
Closed 2 years ago.
I seem to remember that there is a syntax in python to directly input numbers with comma separators (1,000,000 instead of 1000000). Googling the issue gives either results on how to:
Print numbers with comma separators
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
locale.format("%d", 1255000, grouping=True)
Remove commas from numbers to input into python
a = '1,000,000'
int(a.replace(',' , ''))
I don't want to do either and the plethora of results stops me from finding the information I need.
Instead of commas, Python allows the use of underscores.
See https://www.python.org/dev/peps/pep-0515/
grouping decimal numbers by thousands
amount = 10_000_000.0
grouping hexadecimal addresses by words
addr = 0xCAFE_F00D
grouping bits into nibbles in a binary literal
flags = 0b_0011_1111_0100_1110
same, for string conversions
flags = int('0b_1111_0000', 2)
Related
This question already has answers here:
Understanding difference between Double Quote and Single Quote with __repr__()
(3 answers)
Closed 2 years ago.
I have recently started python and am having a frustratingly hard time trying to figure out how to print a raw string containing both ' and " characters. Even with various combinations of r'' and \ I cannot get python to return the literal string that I require.
Goal: Assign string of the following format to variable (similar format to be used as password). String: "1z8'aoVz1+9p}2C (16 character string starting with " and containing ').
Current result:
>>> string ='''"1z8'aoVz1+9p}2C'''
>>> string
'"1z8\'aoVz1+9p}2C'
>>> string =r'"1z8\'aoVz1+9p}2C'
>>> string
'"1z8\\\'aoVz1+9p}2C'
I have also tried splitting it into several variable and concatenating but python always returns the \ before '.
Thank you all for your help. I have learn a lot from this forum.
There is no need for raw string:
string =""""1z8'aoVz1+9p}2C"""
Now, if you do this:
>>> string =""""1z8'aoVz1+9p}2C"""
>>> string
you will get this:
'"1z8\'aoVz1+9p}2C'
but if you print it, you'll get what you want:
"1z8'aoVz1+9p}2C
This question already has answers here:
How to print a number using commas as thousands separators
(30 answers)
Closed 3 years ago.
I am trying to parse a string which contains a number and when I try to convert it to a float, it gives me an error:
ValueError: could not convert string to float: '8,900'
My code:
soup=BeautifulSoup(content,"html.parser")
element=soup.find("div",{"class":"_1vC4OE _3qQ9m1"})
price=element.text
price_without_symbol=price[1:]
print(float(price_without_symbol));
Output:
"C:\Users\SHIVAM TYAGI\PycharmProjects\price-of-
chair1\venv\Scripts\python.exe" "C:/Users/SHIVAM
TYAGI/PycharmProjects/price-of-chair1/src/app.py"
Traceback (most recent call last):
File "C:/Users/SHIVAM TYAGI/PycharmProjects/price-of-chair1/src/app.py",
line 9, in
print(float(price_without_symbol));
ValueError: could not convert string to float: '8,900'
Depending on the numeric convention used, a comma can either denote a thousands separator or a decimal point.
Python float numbers syntax uses a dot (.) as decimal point and an optional underscore (_) as thousand separator, for readability only.
This means you need to know which numerical convention the number you are reading uses.
In your case it would seem you are reading numbers using the US-English numeric convention.
US-English | 4,294,967,295.00
All you need is to remove the comma which acts as thousands separator.
price_without_symbol=price[1:].replace(',', '')
print(float(price_without_symbol))
This question already has answers here:
Replacing instances of a character in a string
(17 answers)
Closed 4 years ago.
i have a .txt file containing mac address with this format f2:e0:e2:e8:3a:5e
how can i convert f2:e0:e2:e8:3a:5e to f2-e0-e2-e8-3a-5e using pyhton and use it as variable?
Open it with open(), read contents to a string with the .read() method and replace colons with hyphens with the .replace() string method. Store the result in a variable.
mac_addr = open('your_file.txt').read().replace(':', '-')
Probably(from the idea/complexity) a little faster than Joe's answer(depends on implementation) :
If you can ensure that your address is always in the format xx:xx:xx:xx:xx:xx [...]
with open('your_file.txt') as file:
address=list(file.read())
for i in range(2, len(address), 2):
address[i]="-"
address="".join(address)
# do stuff with address here
using with as proposed by RoadRunner.
And if you want it blazing fast, look at this :
Fast character replacing in Python's immutable strings
This solution will replace every 2nd character with a hyphen.
This question already has answers here:
Convert an int value to unicode
(4 answers)
Closed 5 years ago.
In Python I'm trying to print out the character corresponding to a given code like this:
a = 159
print unichr(a)
It prints out a strange symbol. Can anyone explain why?
#To get numerical value of string. This gives me 49.
ord("1")
#To get string from numerical value. This gives me "1".
chr(49)
It is possible that the numerical value that you're trying to convert to a digit is the representative of a special character, in which case it is likely that python converted it into it's hex equivalent. To see the hex value of an integer:
hex(ord("1"))
If that is not the case, it's possible that it used another representative, since it is(hypothetically) a special character.
The character at unicode 159 is an Application Program Command. It's a control character, and is deemed not a graphic character.
More information
This question already has answers here:
What exactly do "u" and "r" string prefixes do, and what are raw string literals?
(7 answers)
Closed 6 years ago.
From documentation:
The solution is to use Python’s raw string notation for regular
expression patterns; backslashes are not handled in any special way in
a string literal prefixed with 'r'. So r"\n" is a two-character string
containing '\' and 'n', while "\n" is a one-character string
containing a newline. Usually patterns will be expressed in Python
code using this raw string notation.
Types also match; type(u"text") == type(ur"text"), and same goes when you remove u. Therefore, I have to ask: what is the difference between these two? If there is no difference, why use r at all?
For example:
>>> len(ur"tex\t")
5
>>> len(u"tex\t")
4
Without r, the \t is one character (the tab) so the string has length 4.
Use r if you want to build a regular expression that involves \. In an non-r string, you'd have to escape these which is not funny.
>>> len(u"\\")
1
>>> len(ur"\\")
2