【问题标题】:How to Make 1st Letter of String Upperase with upper() - PYTHON如何使用upper()制作字符串的第一个字母大写 - PYTHON
【发布时间】:2021-03-03 10:46:02
【问题描述】:

我正在尝试将字符串的第一个字母更改为大写。我知道使用capitalize() 或title() 是可行的,但我只是在测试一些东西,想知道如何用upper() 做同样的事情。我尝试过的代码出现错误消息:'TypeError: newS must be a string on line 10'。任何建议将不胜感激!

def uppercase(string):
  string = string.replace(string[0],string[0].upper) 
  return string
print uppercase("hello")

【问题讨论】:

  • return string[0].upper() + string[1:]

标签: python string uppercase


【解决方案1】:

您在调用upper 时错过了(),这是一种方法:

def uppercase(string):
  string = string.replace(string[0],string[0].upper(), 1) 
  return string

print(uppercase("hello"))

此外,正如 deceze 指出的那样,基于 replace() 的方法将按原样失败,您可以将可选的 maxreplace 参数用于 1 以仅替换第一次出现。

【讨论】:

  • 这种方法对于像"haha" 这样的字符串通常会失败……
  • 另外,您似乎正在使用Python2,所以我强烈建议您切换到python3,因为python2 早已失效。
  • 切片方法可以按照 deceze 的建议工作,或者使用可选的 maxreplace 是使其与 replace 本身一起工作的选项。
【解决方案2】:

你可能会这样做

def uppercase(string):
  string = string.replace(string[0],string[0].upper(),1) 
  return string
print uppercase("hello")

注意有.upper(),即方法被调用并且1限制替换的数量,所以aaa会变成Aaa而不是AAA。此解决方案假定 string 永远不会为空 str

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2022-01-09
    • 2013-03-29
    • 2013-06-11
    • 2014-11-26
    • 2017-06-25
    相关资源
    最近更新 更多