Как убрать табуляцию в python
Перейти к содержимому

Как убрать табуляцию в python

  • автор:

Убрать пробелы / табуляции / переводы строк — python

Я пытаюсь удалить все пробелы/табуляции/новые строки в python 2.7 на Linux.

Я написал это, чтобы выполнить эту работу:

Кажется, что это просто, но я кое-что упустил. Должен ли я что-то импортировать?

7 ответов

Используйте str.split([sep[, maxsplit]]) без sep или sep=None :

Если sep не указано или есть None , то другой алгоритм разделения применяется: пробеги последовательных пробелов рассматриваются как одиночные разделитель, и результат не будет содержать пустых строк в начале или end, если строка имеет ведущие или конечные пробелы.

Demo:

Используйте str.join в возвращенном списке, чтобы получить этот вывод:

Если вы хотите удалить несколько элементов пробелов и заменить их на отдельные пробелы, самый простой способ — с регулярным выражением:

Как убрать отступ табуляции с нескольких строк в IDLE?

Если вы хотите сделать отступ для нескольких строк в Python IDLE, просто отметьте строки и нажмите Tab. Но что, если вы хотите убрать отступ с нескольких строк? Shift + Tab не работает в IDLE.

Хороший момент — может потребоваться больше времени, чтобы дождаться ответа SO, но вы получите окраску репутации. — S.Lott

8 ответы

Если вы используете IDLE, вы можете использовать Ctrl+] делать отступы и Ctrl+[ к undent.

ответ дан 26 апр.

хм . Я работаю над норвежской клавиатурой и чтобы сделать ‘[‘, я должен удерживать Alt Gr, но все же он все еще хочет сделать свое дело. — Спасибо

Если вы используете IDLE и на норвежской клавиатуре возникает проблема с Ctrl- [, вы можете изменить ключ.

  1. Перейдите в Параметры-> Настроить IDLE.
  2. Щелкните вкладку Ключи.
  3. При необходимости нажмите «Сохранить как новый настраиваемый набор ключей».
  4. Выбрав свой собственный набор ключей, найдите в списке «dedent-region».
  5. Щелкните Получить новые ключи для выбора.
  6. и т.д

Я попробовал вставить Shift-Tab, и это отлично сработало.

ответ дан 26 апр.

Приятно — могу изменить на shift + tab — Smashery

Да, тот же вопрос и тот же ответ даже сегодня. Спасибо ! : D — Бмс Бхарадвадж

Зависит от вашего редактора.

Вы пробовали Shift + Tab?

ответ дан 26 апр.

Работа в Pycharm — Ансар Ахмед

SHIFT + TAB работает

ответ дан 09 дек ’15, 19:12

Для IDLE выберите строки, затем откройте меню «Формат». (Между «Изменить» и «Выполнить», если у вас возникли проблемы с его поиском.) Это также даст вам сочетание клавиш, для меня оказалось, что это сочетание клавиш было «Ctrl + [»

зависит от вашего редактора.

ответ дан 26 апр.

По умолчанию в IDLE он находится в левой скобке Shift. Однако, если вы хотите, вы можете настроить его как Shift-Tab, щелкнув Параметры -> Настроить IDLE -> Ключи -> Использовать настраиваемый набор ключей -> dedent-region -> Получить новые ключи для выбора

Затем вы можете выбрать любую комбинацию, которую хотите. (Не забудьте нажать «Применить», иначе все настройки не будут затронуты.)

В Jupyter Notebook,

Создан 08 июля ’19, 09:07

Он задает вопрос о простое Python, а не о ноутбуке Jupyter? — Гаял Куруппу

Но часто, даже если кто-то ищет решение для ноутбука Jupyter для того же, эта ссылка появляется. Именно это и случилось со мной. Я подумал о том, чтобы разместить здесь ответ в блокноте. Надеюсь, это имеет для вас смысл, @GayalKuruppu !! — Saurav

no @Saurav SHIFT и SHIFT + TAB универсально используются на большинстве языков. это не только для ноутбука jupyter. Любой другой редактор использует это. IDLE здесь является исключением. Поэтому ответ должен быть конкретным. Кроме того, ваш ответ уже дан как «Попробуйте shift + tab, если вы пользуетесь другими редакторами». Попробуйте добавить к вопросу что-нибудь ценное. — Гаял Куруппу

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками indentation python-idle code-editor or задайте свой вопрос.

15 Easy Ways to Trim a String in Python

15 Easy Ways to Trim a String in Python

Learn how to strip / remove spaces, newline, tabs, special characters, line ending, and more!

Play this article

I’m not gonna lie. There are multiple ways you can trim a string in Python.

But. the truth is, you don’t need to know every one of them.

In this article, you’ll see only the most important techniques, such as stripping leading and trailing spaces (as well as the ones inside the string). You’ll also learn how to remove tabs, newlines, carriage return (CRLF), and other characters. And we’ll be using nothing more than native methods and regex—no external libraries required!

By the end of this article, you’ll have mastered:

How to Trim Characters From a String

Trimming a string means deleting certain chars from the start, the end, or both sides of a string. Removing unwanted chars makes it easier to compare strings and can prevent hard to debug issues.

You can remove any kind o character, but usually what we’re interested in is deleting blank spaces, new lines, carriage return (CRLF), tabs and other special symbols.

In this section, we’re going to see how to remove leading or trailing spaces, blank spaces, newline character, carriage return (CRLF), and tabs.

Stripping Leading Whitespace From Beginning of a String

The str class has a very convenient method to trim leading spaces named str.lstrip , a shorthand for «left-strip», since it trims a string from the left-hand side. You can think of it as a left trim.

using python .lstrip method to remove leading spaces from a string

When calling str.lstrip with no arguments, it removes all whitespaces from left to right. But if all you want is to strip the first char, then there are two ways of doing this. The first one assumes that there will always be at least one whitespace in the beginning of the string. If that’s the case, then you can just slice it.

If there’s no guarantee of that, we’ll need to check first if the string starts with space.

Stripping Trailing Whitespace From End of a String

The way to remove trailing spaces from the end of the string is to use str.rstrip .

This method expects a list of chars and trims the string from the right. It removes all chars that match one of those you passed, and stop as soon as it cannot match anymore. By default, str.rstrip() removes blanks if you don’t pass anything to it. You can think of it as a right trim.

using python .rstrip method to remove trailing spaces from the end of a string

Sometimes you might want to trim only the last character of a string. And we can use the same logic from the previous example. Check if the last char is a space, and use slice to remove it.

Removing Spaces From From Start and End of a String

If all you want is to remove whitespaces from start and end of string, str.strip will serve you better.

This method trims both sides of the string. And just like str.lstrip and str.rstrip , if you can pass any combination of chars as argument, it removes them from both ends.

⚠️ WARNING ⚠️: A common misconception is to think that there’s a trim() function in Python.

using python .strip to remove spaces from both sides of a string

How to Trim Newlines

We’ve seen how str.strip can remove blank spaces from both sides of a string. I’ve also mentioned that this method takes a chars argument that you can use pass a combination of character you want to trim.

To trim line breaks, you can pass \n and it will strip all newlines from both sides of the string.

strip new lines from a string using .strip method

How to Trim Carriage Return (CRLF)

The Carriage Return (CR), and Line Feed (LF) are nothing more than a newline character. They are represented by the concatenation of \r and \n forming \r\n . This is how Microsoft Windows, Symbian OS and other non-Unix operating systems represent a new line [source].

Removing them from a string is the same as removing the single newline. You feed str.strip with \r\n and method does its job!

trimming carriage return - line feed (CRLF) from a string in python

How to Trim Tabs

If you are following this guide from the beginning you might already know how to do this. Trimming tabs from a string in Python is the same as other characters, you use str.strip and pass the ‘\t’ string to it.

stripping tabs from a string using strip method in python

How to Trim a Combination of Characters From a String

As I mentioned before, str.strip takes as argument a string, not just a single char. This sequence of chars is a combination of all chars you want to remove from the beginning and end of your string.

trimming a combination of more than one char from both sides of a string in python

How to Remove Multiple Spaces Inside a String

Sometimes you want to do more than trimming, let’s say you want to remove chars inside the string. There are two ways of doing this: one is to remove only the duplicates; the other is to remove all extra spaces.

Removing Only Duplicates

To remove only the duplicated characters, you can use the regex module re

removing duplicate spaces in a string in python using re module

This method gets rid of all consecutive spaces. What if you want to do not only that, but also trim the string by removing the leading and trailing blanks?

One way is to split the string and then joining then like so:

Removing All Spaces

Now, if you want to strip all whitespace in your string, either use regex or call the str.replace method.

Using re (regex module)

removing all spaces from a string in python using regex

Using replace

removing all spaces from a string using .replace

How to Strip a List of Strings

Trimming a list of strings is almost the same as trimming an individual one. The only difference is that you have to iterate over the list, and call str.strip method on each one. You do so by using a list comprehension, for example, to return a new list with all strings trimmed.

How to Strip an (Numpy) Array of Strings

It’s very common to use Numpy for data science tasks due to its performance and ease to use.

If you have a array of strings and want to trim each one of them, Numpy comes with an efficient vectorized implementation of strip .

In fact, it also has .lstrip , .rstrip , .replace , and many other string operations.

The vectorized versions work slightly differently, they are not a method but a function in the numpy.char module. So you must pass the array and the list of chars you want to trim.

python_numpy_1.png

Conclusion

In this post, you learned several ways of trimming a string in Python, including array of strings. Python allows us to strip leading and trailing characters easily. And if instead of removing the extra chars on each side you want to remove the ones internally, you can count on the regex module. I hope you’ve found this article helpful and see you next time!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *