s = 'the brown fox'
...ここで何かを...
s
次のようにする必要があります。
'The Brown Fox'
これを行う最も簡単な方法は何ですか?
s = 'the brown fox'
...ここで何かを...
s
次のようにする必要があります。
'The Brown Fox'
これを行う最も簡単な方法は何ですか?
文字列の.title()
メソッド (ASCII または Unicode のいずれでも問題ありません) はこれを行います。
>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'
ただし、ドキュメントに記載されているように、アポストロフィが埋め込まれた文字列に注意してください。
このアルゴリズムは、言語に依存しない単純な単語の定義を、連続した文字のグループとして使用します。この定義は多くの文脈で機能しますが、短縮形と所有格のアポストロフィが単語の境界を形成することを意味し、これは望ましい結果ではない可能性があります。
>>> "they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk"
その.title()
方法がうまくいかない、
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
string.capwords()
方法を試して、
import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
capwords に関する Python ドキュメントから:
str.split() を使用して引数を単語に分割し、str.capitalize() を使用して各単語を大文字にし、str.join() を使用して大文字の単語を結合します。オプションの 2 番目の引数 sep が指定されていないか、または None である場合、一連の空白文字は 1 つのスペースに置き換えられ、先頭と末尾の空白は削除されます。それ以外の場合は、単語を分割して結合するために sep が使用されます。
この種のことが私にとって楽しいという理由だけで、ここにさらに2つの解決策があります.
単語に分割し、分割されたグループの各単語の頭文字を大文字にして、再び結合します。これにより、単語を区切る空白が、それが何であれ、単一の空白に変更されます。
s = 'the brown fox'
lst = [word[0].upper() + word[1:] for word in s.split()]
s = " ".join(lst)
編集: 上記のコードを書いたときに何を考えていたか覚えていませんが、明示的なリストを作成する必要はありません。ジェネレーター式を使用して、怠惰な方法でそれを行うことができます。したがって、より良い解決策は次のとおりです。
s = 'the brown fox'
s = ' '.join(word[0].upper() + word[1:] for word in s.split())
正規表現を使用して、文字列の先頭、または単語を区切る空白と単一の非空白文字を一致させます。括弧を使用して「一致グループ」をマークします。一致オブジェクトを受け取り、空白の一致グループを変更せずに返し、空白以外の文字の一致グループを大文字で返す関数を作成します。次にre.sub()
、パターンを置き換えるために使用します。これには、最初のソリューションの句読点の問題はなく、最初のソリューションのように空白をやり直すこともありません。これは最高の結果を生み出します。
import re
s = 'the brown fox'
def repl_func(m):
"""process regular expression match groups for word upper-casing problem"""
return m.group(1) + m.group(2).upper()
s = re.sub("(^|\s)(\S)", repl_func, s)
>>> re.sub("(^|\s)(\S)", repl_func, s)
"They're Bill's Friends From The UK"
この回答を調べてよかったです。re.sub()
関数を取ることができるとは思いもしませんでした!内部で重要な処理を実行re.sub()
して、最終結果を生成できます!
@jibberia anwser のコピー アンド ペースト対応バージョン:
def capitalize(line):
return ' '.join(s[:1].upper() + s[1:] for s in line.split(' '))
str.title() がうまくいかない場合は、自分で大文字化してください。
一発ギャグ:
>>> ' '.join([s[0].upper() + s[1:] for s in "they're bill's friends from the UK".split(' ')])
"They're Bill's Friends From The UK"
明確な例:
input = "they're bill's friends from the UK"
words = input.split(' ')
capitalized_words = []
for word in words:
title_case_word = word[0].upper() + word[1:]
capitalized_words.append(title_case_word)
output = ' '.join(capitalized_words)
提案されたメソッド str.title() は、すべての場合に機能するとは限りません。例えば:
string = "a b 3c"
string.title()
> "A B 3C"
の代わりに"A B 3c"
。
私は、次のようなことをする方が良いと思います:
def capitalize_words(string):
words = string.split(" ") # just change the split(" ") method
return ' '.join([word.capitalize() for word in words])
capitalize_words(string)
>'A B 3c'
単語を大文字にするには...
str = "this is string example.... wow!!!";
print "str.title() : ", str.title();
@ Gary02127コメント、以下のソリューションはアポストロフィ付きのタイトルで機能します
import re
def titlecase(s):
return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(), s)
text = "He's an engineer, isn't he? SnippetBucket.com "
print(titlecase(text))
私はこの答えが本当に好きです:
@jibberia anwser のコピー アンド ペースト対応バージョン:
def capitalize(line):
return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])
しかし、私が送信していた行のいくつかは、s[1:] を実行しようとしたときにエラーの原因となった空白の '' 文字で分割されていました。おそらくこれを行うより良い方法がありますが、次のように、len(s)>0 の場合を追加する必要がありました。
return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])