Убрать ведущие нули python

Как удалить начальные и конечные нули в строке? Python

Желаемый результат для удаления конечных нулей будет:

listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']

Желаемый результат для начальных конечных нулей будет:

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']

Желаемый результат удаления начальных и конечных нулей будет:

listOfNum = ['231512-n','1209123100000-n', 'alphanumeric', 'alphanumeric']

Пока я делаю это следующим образом, пожалуйста, предложите лучший способ, если он есть:

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \ '000alphanumeric'] trailingremoved = [] leadingremoved = [] bothremoved = [] # Remove trailing for i in listOfNum: while i[-1] == "0": i = i[:-1] trailingremoved.append(i) # Remove leading for i in listOfNum: while i[0] == "0": i = i[1:] leadingremoved.append(i) # Remove both for i in listOfNum: while i[0] == "0": i = i[1:] while i[-1] == "0": i = i[:-1] bothremoved.append(i)

удалить как завершающие, так и ведущие нули? Если вас интересует только удаление завершающих нулей, используйте .rstrip вместо них (и .lstrip только для первых).

Вы можете использовать некоторое понимание списка, чтобы получить нужные вам последовательности:

trailing_removed = [s.rstrip("0") for s in listOfNum] leading_removed = [s.lstrip("0") for s in listOfNum] both_removed = [s.strip("0") for s in listOfNum]

@ Чарльз: Да! У меня была такая же проблема, и вы можете это сделать s.strip(«0») or «0» : если ваша строка превращается в пустую строку, она будет оцениваться как False или и будет заменена на нужную строку «0»

Читайте также:  Python read all file in directory

Удалите начальный + завершающий ‘0’:

list = [i.strip('0') for i in listOfNum ]
list = [ i.lstrip('0') for i in listOfNum ]
list = [ i.rstrip('0') for i in listOfNum ]

Вы можете просто сделать это с помощью bool:

if int(number) == float(number): number = int(number) else: number = float(number)

Вы пробовали использовать strip () :

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric'] print [item.strip('0') for item in listOfNum] >>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']

str.strip — лучший подход для этой ситуации, но more_itertools.strip также и общее решение, которое удаляет как ведущие, так и замыкающие элементы из итерации:

import more_itertools as mit iterables = ["231512-n\n"," 12091231000-n00000","alphanum0000", "00alphanum"] pred = lambda x: x in "0", "\n", " "> list("".join(mit.strip(i, pred)) for i in iterables) # ['231512-n', '12091231000-n', 'alphanum', 'alphanum']

подробности

Обратите внимание, здесь мы удаляем как начальные, так и конечные «0» элементы среди других элементов, удовлетворяющих предикату. Этот инструмент не ограничивается струнами.

См. Также документы для получения дополнительных примеров

more_itertools — это сторонняя библиотека, которую можно установить через > pip install more_itertools .

Источник

Remove Leading Zeros in Python String

Remove Leading Zeros in Python String

  1. Use Iteration Statements to Remove Leading Zeros in a String in Python
  2. Use the lstrip() Function Along With List Comprehension to Remove Leading Zeros in a String in Python
  3. Use the startswith() Method + Loop + List Slicing to Remove Leading Zeros in a String in Python

The removal of leading or trailing zeros is essential when data processing is performed, and the data has to be passed forward. A stray 0 might get attached to the string while it is transferred from one place to another, and it is recommended to remove it as it is unnecessary and inconvenient.

This tutorial demonstrates the several ways available to remove leading zeros in a string in Python.

Use Iteration Statements to Remove Leading Zeros in a String in Python

The simplest and most basic way to remove leading zeros in a string in Python is to remove them using iteration statements manually. Here, we manually create a code using a for loop along with the while loop to make a program that removes leading zeros in a string in Python.

The following code uses the for loop to remove leading zeros in a string in Python.

A = ['0001234','01000','1000',] removeleading = []  for x in A:  while x[0] == "0":  x = x[1:]  removeleading.append(x) print(removeleading) 

The above code provides the following output:

In the above code, we use two iteration statements, a for loop and a while loop, the latter being nested within the former. Finally, we append the newly created list and then display it after making the necessary changes.

Use the lstrip() Function Along With List Comprehension to Remove Leading Zeros in a String in Python

The lstrip() can be utilized to remove the leading characters of the string if they exist. By default, a space is the leading character to remove in the string.

List comprehension is a relatively shorter and very graceful way to create lists that are to be formed based on given values of an already existing list.

We can combine these two things and use them in our favor.

The following code uses the lstrip() function along with the list comprehension to remove leading zeros in a string in Python.

A = ['0001234','01000','1000',] res = [ele.lstrip('0') for ele in A] print (str(res)) 

The above code provides the following output.

In the above code, the lstrip() function is used to strip the leading zeros in the given string. List comprehension is used here to extend the logic further and achieve this program successfully without any errors.

Use the startswith() Method + Loop + List Slicing to Remove Leading Zeros in a String in Python

The startswith() method provides a True value when the string starts with the value that the user in the function definition specifies. We combine this startswith() function with a loop and list slicing to remove leading zeros in a string in Python.

The following code uses the startswith() method + loop + list slicing to remove leading zeros in a string in Python.

A = ['0001234','01000','1000'] for idx in range(len(A)):  if A[idx].startswith('0'):  A[idx] = A[idx][1:] print (str(A)) 

The above code provides the following output:

In the above code, a for loop is opened for working, and the list slicing process is done with the help of the startswith() function.

The drawback with this method is that it only removes one leading zero at a run, which can be problematic with big numbers.

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Related Article — Python String

Источник

Убрать ведущие нули python

Last updated: Feb 19, 2023
Reading time · 2 min

banner

# Remove the trailing zeros from a Decimal in Python

To remove trailing zeros from a decimal:

  1. Use the decimal.to_integral() method to check if the number has a fractional part.
  2. If it does, round the number and return it.
  3. If it does not, use the decimal.normalize() method to strip any trailing zeros.
Copied!
from decimal import Decimal num = Decimal('1.230000') def remove_exponent(d): return ( d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() ) print(remove_exponent(num)) # 👉️ 1.23

remove trailing zeros from decimal

The first function is taken from the Decimal FAQ section of the official docs.

The to_integral method rounds to the nearest integer.

Copied!
from decimal import Decimal # 👇️ True print(Decimal('1.0000') == Decimal('1.0000').to_integral()) # 👇️ False print(Decimal('1.9000') == Decimal('1.9000').to_integral()) print(Decimal('1.0000').to_integral()) # 👉️ 1

If the number has no decimal part, we use the quantize() method to round to a fixed number of decimal places.

If the number has a decimal part, we use the Decimal.normalize method to strip the rightmost trailing zeros.

Copied!
from decimal import Decimal print(Decimal('1.230000').normalize()) # 👉️ 1.23 print(Decimal('3.456000000').normalize()) # 👉️ 3.456

We only use the normalize() method if the number has a decimal part because it could remove zeros to the left of the decimal.

Copied!
from decimal import Decimal print(Decimal('500.000').normalize()) # 👉️ 5E+2 print(Decimal('510.100').normalize()) # 👉️ 510.1

Alternatively, you can use the str.rstrip() method.

# Remove trailing zeros from decimal using str.rstrip()

This is a two-step process:

  1. Use the str() class to convert the decimal to a string.
  2. Use the str.rstrip() method to strip the trailing zeros if the number has a decimal point.
Copied!
from decimal import Decimal num = Decimal('1.230000') string = str(num) without_trailing_zeros = string.rstrip( '0').rstrip('.') if '.' in string else string result = Decimal(without_trailing_zeros) print(result) # 👉️ 1.23

remove trailing zeros from decimal using str rstrip

The first step is to convert the decimal to a string.

The str.rstrip method returns a copy of the string with the provided trailing characters removed.

We first strip trailing zeros, then try to strip the dot . if the decimal part only consisted of trailing zeros.

The example also checks whether the string contains a dot, so we don’t attempt to strip trailing zeros from numbers that don’t have a decimal part, e.g. 5000 to 5 .

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Как удалить ведущие и завершающие нули в строке? питон

Желаемый результат для удаления конечных нулей:

listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric'] 

Желаемый результат для ведущих конечных нулей:

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric'] 

Выход желания для удаления начального и конечного нулей будет:

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric'] 

Пока я делаю это следующим образом, предложите лучший способ, если есть:

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \ '000alphanumeric'] trailingremoved = [] leadingremoved = [] bothremoved = [] # Remove trailing for i in listOfNum: while i[-1] == "0": i = i[:-1] trailingremoved.append(i) # Remove leading for i in listOfNum: while i[0] == "0": i = i[1:] leadingremoved.append(i) # Remove both for i in listOfNum: while i[0] == "0": i = i[1:] while i[-1] == "0": i = i[:-1] bothremoved.append(i) 

ОТВЕТЫ

Ответ 1

удалить как конечный, так и ведущий нули? Если вас интересует только удаление нужных нулей, используйте .rstrip вместо (и .lstrip только для ведущих).

[Дополнительная информация в doc.]

Вы можете использовать некоторое понимание списка, чтобы получить нужные вам последовательности:

trailing_removed = [s.rstrip("0") for s in listOfNum] leading_removed = [s.lstrip("0") for s in listOfNum] both_removed = [s.strip("0") for s in listOfNum] 

Ответ 2

Удалить ведущий + трейлинг «0»:

list = [i.strip('0') for i in listOfNum ] 
list = [ i.lstrip('0') for i in listOfNum ] 
list = [ i.rstrip('0') for i in listOfNum ] 

Ответ 3

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric'] print [item.strip('0') for item in listOfNum] >>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric'] 

Ответ 4

Вы можете просто сделать это с помощью bool:

if int(number) == float(number): number = int(number) else: number = float(number) 

Ответ 5

strip — лучший подход для этой ситуации, но more_itertools.strip является общим решением, которое разбивает ведущие и конечные элементы из итерация:

import more_itertools as mit iterables = ["231512-n\n"," 12091231000-n00000","alphanum0000", "00alphanum"] pred = lambda x: x in list("".join(mit.strip(i, pred)) for i in iterables) # ['231512-n', '12091231000-n', 'alphanum', 'alphanum'] 

Обратите внимание: здесь мы разделяем как ведущие, так и конечные «0» среди других элементов, которые удовлетворяют предикату. Этот инструмент не ограничивается строками. Подробнее см. в документах.

Источник

Оцените статью