用最恐怖的方式替换第一个和最后一个字符串

时间:2012-11-29 01:50:53

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

5 个答案:

答案 0 :(得分: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. 

答案 1 :(得分: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.'

答案 2 :(得分: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.

答案 3 :(得分: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.']

答案 4 :(得分: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)