Как убрать 0b в python



Скачай курс
в приложении
Перейти в приложение
Открыть мобильную версию сайта
© 2013 — 2023. Stepik
Наши условия использования и конфиденциальности

Public user contributions licensed under cc-wiki license with attribution required
Как убрать знаки перед значениями, после перевода с помощью bin(), oct(), hex()?

каким кодом можно убрать эти знаки перед числами: Спасибо за ответы
Отслеживать
задан 23 мая 2021 в 14:01
41 4 4 бронзовых знака
num[2:] — можно так
23 мая 2021 в 14:08
@TigerTV.ru благодарю
23 мая 2021 в 14:10
@MaidLine Можно ещё переводить не функциями, а через format: f»<100:o>» f»» f»» Тогда префиксов не будет. Причём это даже в документации к Python предлагается.100:o>
23 мая 2021 в 14:25
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
Официальная документация по Python предлагает использовать функции форматирования чтобы сразу получить строки без префиксов.
>>> '%o' % 100 '144' >>> format(100, 'o') '144' >>> f'' '144'
Ну и по аналогии b и x вместо bin() и hex() соответственно.
Отслеживать
ответ дан 23 мая 2021 в 14:35
13.4k 1 1 золотой знак 8 8 серебряных знаков 23 23 бронзовых знака
- python
- python-3.x
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.10.27.43697
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Удалить 0b в двоичном
Используйте операцию среза для удаления первых двух символов.
In [1]: x = 17 In [2]: y = bin(x)[2:] In [3]: y Out[3]: '10001'
Vedang Mehta 22 май 2016, в 18:43
Поделиться
использовать операцию python string slice .
a = bin(17) b = bin(17)[2:]
чтобы отформатировать это до 8 бит, используйте zfill .
c = b.zfill(8)
Tanu 22 май 2016, в 20:13
Поделиться
print (bin(int(input().strip()))[2:])
Питонический способ решить.;)
Ayan Banerjee 07 сен. 2017, в 09:19
Поделиться
Легко просто выполнить эту функцию:
def f(n):print(''.format(n)) f(17) >>> 10001
just 4 help 06 июнь 2017, в 16:26
Поделиться
Ещё вопросы
- 1 Выбор нескольких узлов на одном уровне с LINQ
- 0 PHP в JavaScript с помощью кнопки «Отправить»
- 0 Как я могу хранить отдельное изображение в отдельном поле с одним кодом PHP
- 1 Javascript document.cookie = «ключ = значение» добавляется вместо замены
- 1 Линейный график D3 JS начинается с 0
- 1 Список вне диапазона
- 1 Что не так с этим VenuesExplore?
- 0 Источник данных combobox knockout-kendo не обновляется после его визуализации?
- 0 Двухфакторная аутентификация Qt c ++
- 0 Ajax In QueryMethod Вызов в классическом Asp для отправки электронной почты
- 0 Laravel PHP: обновленный файл интерфейса репозитория не распознается
- 0 цикл через набор элементов и анимировать
- 1 UUID генерируется с использованием двух языков программирования?
- 1 Модификация LiveDataCallAdapter не вызывает функцию адаптации (вызов)
- 0 Невозможно войти в phpMyAdmin
- 1 Javascript на стороне клиента: как получить заголовок ответа HTTP-запроса, когда CORS не разрешен?
- 1 Как исправить ошибку Layoutinflator not found?
- 0 Гоночная игра на с / с ++ с графикой
- 0 Изменить .htaccess на работу? _Escaped_fragment_ = URL
- 0 настройка типа ввода в ng-repeat
- 1 Защита от фильтрации пустого объекта JS
- 0 Не удается получить доступ к AWS RDS MySQL + PHP на Heroku
- 1 Настройка аннотации Springs3 Hibernate3
- 0 Как создать ссылки с использованием JSON, которые при нажатии отображаются в отдельном элементе ?
- 0 Ошибка проверки формы при использовании тега ion-scroll
- 0 Создайте дерево из многомерного массива PHP, используя результаты mysql
- 0 Убрать пробел между строкой таблицы
- 1 построить динамический массив для charts.js
- 0 Принятие значений динамически создаваемых текстовых полей ввода HTML в C #
- 1 URLDownloadToFile загрузка половины файла
- 0 Эффект аккордеона при наведении мыши с переходами шаток
- 1 Возможно ли, что getInstallerPackageName () имеет значение null, когда приложение загружено из Google Play Store?
- 1 Собственный Android Inapp Покупка Где настроить лицензионный ключ RSA в кодировке Base64?
- 1 Датагрид привязка МВВМ
- 0 Доступ к HTML внутри холста
- 1 Есть ли разница между клиентом MDI, контейнером MDI и родителем MDI?
- 1 Показать Recyclerview внутри alertDialog
- 0 Вычеркнуть несколько текстов в опции выбора
- 0 JQuery загрузить страницу в диалог
- 1 Невозможно запустить тест из-за appium appiumDriver
- 0 Выберите не связывать с моделью
- 0 Создавайте динамические тесты с PHPUnit
- 0 Почему javascript (jquery), если операторы не работают, как операторы php if? И что такое решение?
- 1 Используйте методы получения и установки класса Kotlin Model внутри Android Activity
- 0 Можем ли мы иметь автоматическую предустановку AspectRatio для выходных файлов из AWS Elastic Transcoder?
- 0 Группа флажков
- 0 Использование MySQL REGEX для сопоставления повторяющихся номеров в телефонных номерах
- 0 проверка, сколько у div определенного класса
- 0 $ injector: unpr Неизвестный поставщик
- 0 высокая диаграмма с фильтрацией диапазона дат
How can I make `bin(30)` return `00011110` instead of `0b11110`? [duplicate]
What does the b stand for in the output of bin(30) : 0b11110 ? Is there any way I can get rid of this b ? How can I get the output of bin() to always return a standard 8 digit output?
9,959 3 3 gold badges 25 25 silver badges 46 46 bronze badges
asked Sep 8, 2009 at 17:53
5,242 23 23 gold badges 71 71 silver badges 81 81 bronze badges
7 Answers 7
Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than len(s).
>>> bin(30)[2:].zfill(8) '00011110' >>>
6,860 20 20 gold badges 39 39 silver badges 51 51 bronze badges
answered Sep 8, 2009 at 18:02
83.7k 10 10 gold badges 77 77 silver badges 105 105 bronze badges
What about negative numbers?
Jul 25, 2013 at 7:14
Surprisingly this appears to be the fastest, but ackkkk.
Jan 15, 2015 at 22:07
@loannis Your edit caused problems because now the wrong result was provided for negative values, -30 != 30 whereas your edit results in bin(30).lstrip(‘-0b’).zfill(8) == bin(-30).lstrip(‘-0b’).zfill(8)
Jan 17, 2018 at 12:50
0b is like 0x — it indicates the number is formatted in binary (0x indicates the number is in hex).
To strip off the 0b it’s easiest to use string slicing: bin(30)[2:]
And similarly for format to 8 characters wide:
('00000000'+bin(30)[2:])[-8:]
Alternatively you can use the string formatter (in 2.6+) to do it all in one step:
"".format(30)
1 1 1 silver badge
answered Sep 8, 2009 at 17:56
Douglas Leeder Douglas Leeder
52.5k 9 9 gold badges 94 94 silver badges 137 137 bronze badges
+1 for string.format answer, beat me to it
Sep 8, 2009 at 18:30
For this case I prefer the format built in function instead of the format method: format(30, ’08b’) as opposed to «<0:08b>«.format(30)0:08b>
Sep 8, 2009 at 22:23
Don’t use str.format() for a single placeholder and nothing else. That’s what we have format() for: format(30, ’08b’)
Oct 1, 2019 at 20:35
Take advantage of the famous format() function with the lesser known second argument and chain it with zfill()
‘b’ — Binary ‘x’ — Hex ‘o’ — Octal ‘d’ — Decimal
>>> print format(30, 'b') 11110 >>> print format(30, 'b').zfill(8) 00011110
Should do. Here ‘b’ stands for binary just like ‘x’ , ‘o’ & ‘d’ for hexadecimal, octal and decimal respectively.
answered Apr 4, 2014 at 13:02
12.9k 6 6 gold badges 60 60 silver badges 85 85 bronze badges
You can use format in Python 2 or Python 3:
>> print( format(15, '08b') ) 00001111
answered Oct 6, 2017 at 23:05
151 3 3 silver badges 8 8 bronze badges
You can use this too :
bi=bin(n)[2:]
This will remove the ‘0b’ portion of the returned value and you can use the output anywhere .
answered Jan 17, 2018 at 12:37
Akash Kandpal Akash Kandpal
3,136 28 28 silver badges 25 25 bronze badges
The current answers don’t consider negative values (thanks @Gui13 for the comment!) in which case you get -0b. instead of just 0b. . You can handle both with a simple if-else where the value is checked whether it’s less than zero or not
>>> def printBit(x): if x < 0: return '-' + bin(x)[3:].zfill(8) # replace else: return bin(x)[2:].zfill(8) >>> print(printBit(30)) '00011110' >>> print(printBit(-30)) '-00011110'
or by using replace()
>>> print(bin(30)).replace('0b', '').zfill(8)
The problem with the call above is that one of the bits gets «lost» to the — sign due to the same value being used for the zfill() . You can handle this too with a simple ternary check:
>>> x = 30 >>> print(bin(x)).replace('0b', '').zfill(9 if x < 0 else 8) '00011110' >>> x = -30 >>> print(bin(x)).replace('0b', '').zfill(9 if x < 0 else 8) '-00011110'
Last but not least you can also make the zfill() to automatically adapt the number of 0 s to match a byte (8 bits) or a n number of bit quadruplets (4 bits):
>>> def pb(x): bres = bin(x).replace('0b', '').replace('-', '') # If no minus, second replace doesn't do anything lres = len(bres) # We need the length to see how many 0s we need to add to get a quadruplets # We adapt the number of added 0s to get full bit quadruplets. # The '-' doesn't count since we want to handle it separately from the bit string bres = bres = ('-' if x < 0 else '') + bres.zfill(lres + (4-lres%4)) return bres >>> print(pb(7)) '0111' >>> print(pb(-7)) '-0111' >>> print(pb(30)) '00011110' >>> print(pb(-30)) '-00011110'
Here is the final version with adaptable filling of 0 s and additional split with space every n characters (where the n is determined by filling factor):
>>> def pb(x, fillingBits=4, splitWithSpace=True): # If no minus, second replace doesn't do anything bres = bin(x).replace('0b', '').replace('-', '') lres = len(bres) bres = bres.zfill(lres + (fillingBits - (lres % fillingBits))) lres = len(bres) # We can also add a blank after every fillingBits character if splitWithSpace: bres = ' '.join([bres[i:(i + fillingBits)] for i in range(0, lres, fillingBits)]) bres = ('-' if x < 0 else '') + bres # We remove any trailing/leading blanks (occurring whenever splitWithSpace enabled) return bres.strip() >>> print(pb(7)) '0111' >>> print(pb(-7)) '-0111' >>> print(pb(30)) '0001 1110' >>> print(pb(-30)) '-0001 1110'