Вырезать строку до символа python

Как обрезать строку до определенного символа в Python?

Как обрезать строку до определенного символа в Python?

2 ответа

@ johnpaul.blick  Самым простым способом обрезания строки до определенного символа является метод строки . partition

Данный метод разделяет строку на 3 части ( До разделителя, сам разделитель и после разделителя )

string = "Сегодня в лесу нашлось множество ягод - все будут сыты" print(string.partition('-')[0]) # Вывод : Сегодня в лесу нашлось множество ягод 

Вы можете использовать метод str.index() для нахождения индекса определенного символа в строке и затем использовать срезы для обрезания строки до этого символа. Например:

original_string = "This is the original string" cutoff_character = " " cutoff_index = original_string.index(cutoff_character) truncated_string = original_string[:cutoff_index] print(truncated_string) 

Этот код будет обрезать строку «This is the original string» до символа » » (пробела) и выведет строку «This».

Источник

Вырезать строку до символа python

Last updated: Feb 21, 2023
Reading time · 4 min

banner

# Table of Contents

# Truncate a string in Python

Use string slicing to truncate a string, e.g. result = my_str[:5] . The slice returns the first N characters of the string.

Ellipsis can be added to the end of the substring if the string is longer than the slice.

Copied!
my_str = 'bobbyhadz.com' result = my_str[:5] print(result) # 👉️ bobby

truncate string in python

We used string slicing to truncate a string.

The syntax for string slicing is my_str[start:stop:step] .

Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(my_str) — 1 .

The stop index is exclusive (up to, but not including), so the slice returns the first N characters of the string.

Copied!
my_str = 'bobbyhadz.com' result = my_str[:5] print(result) # 👉️ bobby

The example returns a substring containing the first 5 characters of the string.

# Truncate a string with an ellipsis in Python

You can use the ternary operator to add an ellipsis if the string is longer than the slice.

Copied!
my_str = 'bobbyhadz.com' result = my_str[:5] + '. ' if len(my_str) > 5 else my_str print(result) # 👉️ bobby.

truncate string with an ellipsis

The expression to the left of the if statement is returned if the condition is met, otherwise, the string gets returned as is.

# Creating a reusable function

If you have to do this often, define a reusable function.

Copied!
def truncate_string(string, length, suffix='. '): return string[:length] + suffix print(truncate_string('bobbyhadz.com', 3)) # bob. print(truncate_string('bobbyhadz.com', 5)) # bobby. print(truncate_string('bobbyhadz.com', 7)) # bobbyha.

creating reusable function

The function takes a string, the desired length and optionally a suffix as parameters and truncates the given string to the specified length.

Читайте также:  Php удалить два последних символа строки

# Truncate a string using a formatted string literal

Alternatively, you can use a formatted string literal.

Copied!
my_str = 'bobbyhadz.com' result = f'my_str:.5>' print(result) # 👉️ bobby result = f'my_str:.5>". " if len(my_str) > 5 else "">' print(result) # 👉️ bobby.

truncate string using formatted string literal

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Copied!
var1 = 'bobby' var2 = 'hadz' result = f'var1>var2>' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces — .

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

Copied!
my_str = 'bobbyhadz.com' result = f'my_str:.5>' print(result) # 👉️ bobby

The digit after the period is the maximum size of the string.

The example formats the string to a maximum of 5 characters.

You can use the ternary operator to add an ellipsis if the string is longer than the slice.

Copied!
my_str = 'bobbyhadz.com' result = f'my_str:.5>". " if len(my_str) > 5 else "">' print(result) # 👉️ bobby.

# Truncate a string using str.rsplit()

If you need to remove the last word from a string, use the str.rsplit() method.

Copied!
my_str = 'bobby hadz com' new_str = my_str.rsplit(' ', 1)[0] print(new_str) # 👉️ 'bobby hadz'

truncate string using str rsplit

The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.

Copied!
my_str = 'bobby hadz com' print(my_str.rsplit(' ')) # 👉️ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # 👉️ ['bobby hadz', 'com']

The method takes the following 2 arguments:

Name Description
separator Split the string into substrings on each occurrence of the separator
maxsplit At most maxsplit splits are done, the rightmost ones (optional)

If you need to remove the last 2 words from a string, set the maxsplit argument to 2 and access the list item at index 0 .

Copied!
my_str = 'bobby hadz com' # 👇️ remove last word from string result = my_str.rsplit(' ', 1)[0] print(result) # 👉️ bobby hadz # 👇️ remove last 2 words from string result = my_str.rsplit(' ', 2)[0] print(result) # 👉️ bobby

The maxsplit argument can be set to split the string at most N times from the right.

# Truncate a string using textwrap.shorten()

You can also use the textwrap.shorten() method to truncate a string.

Copied!
import textwrap a_string = 'bobby hadz com one two three' new_string = textwrap.shorten(a_string, width=8, placeholder='') print(new_string) # 👉️ bobby new_string = textwrap.shorten(a_string, width=8, placeholder='. ') print(new_string) # 👉️ bobby. new_string = textwrap.shorten(a_string, width=15, placeholder='. ') print(new_string) # 👉️ bobby hadz.

The textwrap.shorten method takes a string, the max width of the string and a placeholder as parameter and truncates the string.

The method collapses and truncates the string to fit in the given width.

Note that the placeholder is included in the width of the string.

Copied!
import textwrap a_string = 'bobby hadz com one two three' new_string = textwrap.shorten(a_string, width=5, placeholder='. ') print(new_string) # 👉️ .

The first word + the placeholder exceeds the specified max width of 5 , so only the placeholder is returned.

The textwrap.shorten() method:

  1. Collapses the whitespace (replaces multiple, consecutive spaces with a single space).
  2. If the result fits in the specified width, it is returned.
  3. Otherwise, enough words are dropped from the end of the string so that the remaining words plus the placeholder fit within the specified width .

# Truncate a string using str.format()

You can also use the str.format() method to truncate a string.

Copied!
a_string = 'bobby hadz com one two three' new_str = ''.format(a_string) print(new_str) # 👉️ bobby new_str = ''.format(a_string) print(new_str) # 👉️ bobby h new_str = ''.format(a_string) print(new_str) # 👉️ bob

The digit after the period is used to specify how many characters are going to be used from the string.

The str.format method performs string formatting operations.

Copied!
first = 'bobby' last = 'hadz' result = "Name: <> <>".format(first, last) print(result) # 👉️ "Name: bobby hadz"

The string the method is called on can contain replacement fields specified using curly braces <> .

You can use the ternary operator if you need to add an ellipsis if the string has a length of more than N.

Copied!
a_string = 'bobby hadz com one two three' new_str = ''.format(a_string) + ". " if len(a_string) > 5 else "" print(new_str) # 👉️ bobby.

The string in the example has more than 5 characters, so the if statement runs and an ellipsis is added at the end.

Want to learn more about truncating strings in Python ? Check out these resources: Get the first N characters of a String in Python ,Remove the last N characters from a String in Python.

# 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.

Источник

How to remove the left part of a string?

I have some simple python code that searches files for a string e.g. path=c:\path , where the c:\path part may vary. The current code is:

def find_path(i_file): lines = open(i_file).readlines() for line in lines: if line.startswith("Path="): return # what to do here in order to get line content after "Path mt24 mb12">
    pythonstring
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this question
)">edited Sep 11, 2019 at 23:08
Boris Verkhovskiy
14.5k11 gold badges100 silver badges101 bronze badges
asked Mar 1, 2009 at 15:19
1
    Be aware that you are returning on the first line occurrence within the file that starts with "Path=". Other answers to this post also do. But if the file is something like a DOS batch file you may actually want the last line occurrence from such a file depending if the "batch" or command file isn't filled with conditionals.
    – DevPlayer
    Aug 27, 2016 at 23:29
Add a comment|

21 Answers 21

Reset to default
210

If the string is fixed you can simply use:

if line.startswith("Path =" in line: param, value = line.split(" Path" and value is the rest after the first =.

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Jul 15, 2011 at 19:54
John Zwinck
239k38 gold badges321 silver badges435 bronze badges
answered Mar 1, 2009 at 15:26
7
    5
    +1 for the split method, avoids the slight ugliness of the manual slicing on len(prefix).
    – bobince
    Mar 1, 2009 at 16:38
    1
    But also throws if your input isn't all in the form "something=somethingelse".
    – Dan Olson
    Mar 1, 2009 at 22:17
    1
    That's why I put the condition in front so it's only used if a "=" is in the string. Otherwise you can also test for the length of the result of split() and if it's ==2.
    – MrTopf
    Mar 1, 2009 at 22:33
    8
    Like Dan Olson says split throws an exception if the delimiter is not present. partition is more stable, it also splits a string and always returns a three-element tuple with pre-, delimiter, and post-content (some of which may be '' if the delimiter was not present). Eg, value = line.partition('=').
    – Anders Johansson
    Jan 3, 2013 at 14:21
    1
    Split doesn't throw an exception if the delimited is not present, it returns a list with the whole string. At least under python 2.7
    – Maxim
    Aug 10, 2017 at 11:30
|Show 2 more comments
135

Remove prefix from a string

# . if line.startswith(prefix): return line[len(prefix):]

Split on the first occurrence of the separator via str.partition()

def findvar(filename, varname="Path", sep=" http://docs.python.org/library/configparser.html" rel="noreferrer">ConfigParser 
from ConfigParser import SafeConfigParser config = SafeConfigParser() config.read(filename) # requires section headers to be present path = config.get(section, 'path', raw=1) # case-insensitive, no interpolation 

Источник

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