7

我正在寻找最pythonic的方法来替换字符串的第一个和最后一个单词(由于各种原因,以字母为基础进行操作是行不通的)。为了演示我正在尝试做的事情,这里有一个例子。

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 的内置方法更好地完成这项工作的意见感兴趣,反之亦然。

4

5 回答 5

7
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. 
于 2012-11-29T02:11:12.947 回答
1

这对你有用吗:

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.'
于 2012-11-29T01:55:34.937 回答
1

这是一个正则表达式解决方案:

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.
于 2012-11-29T02:09:09.453 回答
0

类似于inspectorG4dget,但使用.rsplit()给它maxsplit参数,而.capitalize()不是。

注意:.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.']
于 2012-11-29T02:26:47.613 回答
0
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)
于 2012-11-29T02:33:40.393 回答