使用python代码在句子中首字母大写

时间:2014-01-19 13:36:23

标签: python regex string

下面的代码将“w”中单词的第一个单词大写。我想知道函数captilize(句子)是如何工作的?具体来说,sentence.split会做什么?

`

import random

def test():
  w = ["dog", "cat", "cow", "sheep", "moose", "bear", "mouse", "fox", "elephant",    "rhino", "python"]
  s = ""

  #random.seed(rnd_seed)

  for i in range(0, random.randint(10,15)):
    s += random.choice(w) + " "
  print "<ignore>Sentence: " + s
  print "Capitalized: " + capitalize(s).strip()


def capitalize(sentence):
  w = sentence.split()
  ww = ""
  for word in w:
    ww += word.capitalize() + " "
  return ww


test()`

1 个答案:

答案 0 :(得分:0)

<强> .split(SEP): 具体的split方法接受一个字符串,并使用sep作为分隔符字符串返回字符串中单词的列表。如果没有传递分隔符值,则将空格作为分隔符。

例如:

a = "This is an example"
a.split()        # gives ['This', 'is', 'an', 'example']  -> same as a.split(' ')

谈到你的功能,它以字符串的形式接受一个句子并返回每个单词大写的句子。让我们逐行看:

def capitalize(sentence):    # sentence is a string
  w = sentence.split()       # splits sentence into words eg. "hi there" to ['hi', there']
  ww = ""                   # initializes new string to empty
  for word in w:                 # loops over the list w
    ww += word.capitalize() + " "      # and capitalizes each word and adds to new list ww
  return ww                               # returns the new list