Заменить первое и последнее слово строки в наиболее подходящие для Python способ
Я ищу самый питонический способ заменить первое и последнее слово строки (делать это на основе буквы не будет работать по разным причинам). Чтобы продемонстрировать, что я пытаюсь сделать, вот пример.
a = "this is the demonstration sentence."
Я хотел бы, чтобы результат моей функции python был:
b = "This is the demonstration Sentence."
хитрая часть заключается в том, что могут быть пробелы спереди или в конце строки. Их нужно сохранить.
вот что я имею в виду:
a = " this is a demonstration sentence. "
результат должен быть:
b = " This is a demonstration Sentence. "
также было бы интересно узнать, будет ли регулярное выражение выполнять эту работу лучше, чем встроенные методы python, или наоборот.
5 ответов
import re
a = " this is a demonstration sentence. "
print(re.sub(r'''(?x) # VERBOSE mode
( #
^ # start of string
\s* # zero-or-more whitespaces
\w # followed by an alphanumeric character
)
| # OR
(
\w # an alphanumeric character
\S* # zero-or-more non-space characters
\s* # zero-or-more whitespaces
$ # end of string
)
''',
lambda m: m.group().title(),
a))
доходность
This is a demonstration Sentence.
работает ли это для вас:
In [9]: a = "this is the demonstration sentence."
In [10]: left, _, right = a.strip().partition(' ')
In [11]: mid, _, right = right.rpartition(' ')
In [12]: Left = left.title()
In [13]: Right = right.title()
In [14]: a = a.replace(left, Left, 1).replace(right, Right, 1)
In [15]: a
Out[15]: 'This is the demonstration Sentence.'
вот в regex решение:
def cap(m):
return m.group(0).title()
re.sub(r'(?:^\s*\w+)|(?:[^\s]+\s*$)',cap," this is a demonstration sentence. ")
' This is a demonstration Sentence. '
извините, это лучшее, что я могу сделать ...
срыв регулярных выражений:
(?:^\s*\w+) #match (optional) whitespace and then 1 word at the beginning of the string
| #regex "or"
(?:[^\s]+\s*$) #match a string of non-whitespace characters followed by (optional) whitespace and the end of the line.
подобно inspectorG4dget, но с помощью .rsplit()
давая ему maxsplit и .
Примечание: .split()
также принимает необязательный maxsplit аргумент, чтобы разделить слева.
>>> a = " this is a demonstration sentence. "
>>> part_one, part_two = a.rsplit(" ", 1)
>>> " ".join([part_one.capitalize(), part_two.capitalize()])
'This is the demonstration Sentence.'
.rsplit()
разбивает текст справа, где maxsplit аргумент говорит ему, сколько расщеплений выполнить. Значение 1
дам тебе один "сплит " справа.
>>> a.rsplit(" ", 1)
['this is the demonstration', 'sentence.']
sentence = " this is a demonstration sentence. "
sentence = sentence.split(' ') # Split the string where a space occurs
for word in sentence:
if word: # If the list item is not whitespace
sentence[sentence.index(word)] = word.title()
break # now that the first word's been replaced, we're done
# get the last word by traversing the sentence backwards
for word in sentence[::-1]:
if word:
sentence[sentence.index(word)] = word.title()
break
final_sentence = ' '.join(sentence)