字符串

一.使用方法修改字符串的大小写

  1. name = "ada lovelace"
  2. print(name.title())
  1. Ada Lovelace
  1. name = "Ada Lovelace"
  2. print(name.upper())
  3. print(name.lower())
  1. ADA LOVELACE
  2. ada lovelace

二.合并(拼接)字符串

  1. first_name = "ada"
  2. last_name = "lovelace"
  3. full_name = first_name + " " + last_name
  4. print(full_name)
  1. ada lovelace

三.使用制表符或换行符来添加空白

  1. >>> print("Python")
  2. Python
  3. >>> print("\tPython")
  4. Python
  1. >>> print("Languages:\nPython\nC\nJavaScript")
  2. Languages:
  3. Python
  4. C
  5. JavaScript
  1. >>> print("Languages:\nPython\nC\nJavaScript")
  2. Languages:
  3. Python
  4. C
  5. JavaScript

四.删除空白

  1. >>> favorite_language = 'python '
  2. >>> favorite_language 'python '
  3. >>> favorite_language.rstrip()
  4. 'python'
  5. >>> favorite_language
  6. 'python '

要永久删除这个字符串中的空白,必须将删除操作的结果存回到变量中:

  1. >>> favorite_language = 'python '
  2. >>> favorite_language = favorite_language.rstrip()
  3. >>> favorite_language
  4. 'python'

你还可以剔除字符串开头的空白,或同时剔除字符串两端的空白。为此,可分别使用方法lstrip() 和strip() 。

五.使用字符串时避免语法错误

  1. message = "One of Python's strengths is its diverse community."
  2. print(message)

撇号位于两个双引号之间,因此Python解释器能够正确地理解这个字符串
然而,如果你使用单引号,Python将无法正确地确定字符串的结束位置

  1. message = 'One of Python's strengths is its diverse community.'
  2. print(message)