Python file line startswith

How to remove lines starting with any prefix using Python?

Given a text file, read the content of that text file line by line and print only those lines which do not start with defined prefix. Also store those printed lines in another text file. There are following ways in which this task can be done:

Method 1: Using loop and startswith().

In this method, we read the contents of file line by line. While reading, we check if the line begins with the given prefix, we simply skip that line and print it. Also store that line in another text file.

Suppose the text file from which lines should be read is given below:

Python3

It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing TextGenerator passages, and more recently with desktop publishing software like Albus Potter including versions of TextGenerator.

Updated Text File after removing lines starting with “TextGenerator”

In the above example, we open a file and read its content line by line. We check if that line begins with given prefix using startswith() method. If that line begins with “TextGenerator” we skip that line, else we print the line and store it in another file. In this way, we could remove lines starting with specified prefix.

Читайте также:  border-top-style

Time complexity: O(n) where n is the number of lines in the text file. This is because the program is reading each line one by one and checking if it starts with “TextGenerator”.

Auxiliary space: O(1) as the program is not using any extra space other than the memory required to store the two file objects and a variable to store each line of the file.

In this method we use re module of python which offers a set of metacharacters. Metacharacters are characters with special meaning. To remove lines starting with specified prefix, we use “^” (Starts with) metacharacter.

We also make use of re.findall() function which returns a list containing all matches.

Источник

Метод startswith() в Python

Метод startswith() возвращает True, если строка начинается с указанного префикса (строки). Если нет, возвращается False.

str.startswith(prefix[, start[, end]])

Параметры

Метод в Python принимает не более трех параметров:

  • prefix ‒ строка или кортеж проверяемых строк;
  • start (необязательно) ‒ начальная позиция, в которой должен быть проверен префикс в строке;
  • end (необязательно) ‒ конечная позиция, в которой необходимо проверить префикс в строке.

Возвращаемое значение

  • Он возвращает True, если строка начинается с указанного префикса.
  • Он возвращает False, если строка не начинается с указанного префикса.

Пример 1: Без параметров start и end

text = "Python is easy to learn." result = text.startswith('is easy') # returns False print(result) result = text.startswith('Python is ') # returns True print(result) result = text.startswith('Python is easy to learn.') # returns True print(result)

Пример 2: С параметрами start и end

text = "Python programming is easy." # start parameter: 7 # 'programming is easy.' string is searched result = text.startswith('programming is', 7) print(result) # start: 7, end: 18 # 'programming' string is searched result = text.startswith('programming is', 7, 18) print(result) result = text.startswith('program', 7, 18) print(result)

Передача кортежа

В Python можно передать кортеж префиксов в метод startswith(). Если строка начинается с любого элемента кортежа, команда возвращает True. Если нет, возвращается False.

Читайте также:  Java find all matches string

Пример 3: С префиксом кортежа

text = "programming is easy" result = text.startswith(('python', 'programming')) # prints True print(result) result = text.startswith(('is', 'easy', 'java')) # prints False print(result) # With start and end parameter # 'is easy' string is checked result = text.startswith(('programming', 'easy'), 12, 19) # prints False print(result)

Если вам нужно проверить, заканчивается ли строка указанным суффиксом, вы можете использовать метод endwith() в Python.

Источник

Python String startswith() Method

The startswith() method returns True if the string starts with the specified value, otherwise False.

Syntax

Parameter Values

Parameter Description
value Required. The value to check if the string starts with
start Optional. An Integer specifying at which position to start the search
end Optional. An Integer specifying at which position to end the search

More Examples

Example

Check if position 7 to 20 starts with the characters «wel»:

txt = «Hello, welcome to my world.»

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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