- Как обрезать строку до определенного символа в Python?
- 2 ответа
- Вырезать строку до символа python
- # Table of Contents
- # Truncate a string in Python
- # Truncate a string with an ellipsis in Python
- # Creating a reusable function
- # Truncate a string using a formatted string literal
- # Truncate a string using str.rsplit()
- # Truncate a string using textwrap.shorten()
- # Truncate a string using str.format()
- # Additional Resources
- How to remove the left part of a string?
- Remove prefix from a string
- Split on the first occurrence of the separator via str.partition()
Как обрезать строку до определенного символа в 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
# 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
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.
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.
The function takes a string, the desired length and optionally a suffix as parameters and truncates the given string to the specified length.
# 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.
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'
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:
- Collapses the whitespace (replaces multiple, consecutive spaces with a single space).
- If the result fits in the specified width, it is returned.
- 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