字符串
一.使用方法修改字符串的大小写
name = "ada lovelace"
print(name.title())
Ada Lovelace
name = "Ada Lovelace"
print(name.upper())
print(name.lower())
ADA LOVELACE
ada lovelace
二.合并(拼接)字符串
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
ada lovelace
三.使用制表符或换行符来添加空白
>>> print("Python")
Python
>>> print("\tPython")
Python
>>> print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript
>>> print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript
四.删除空白
>>> favorite_language = 'python '
>>> favorite_language 'python '
>>> favorite_language.rstrip()
'python'
>>> favorite_language
'python '
要永久删除这个字符串中的空白,必须将删除操作的结果存回到变量中:
>>> favorite_language = 'python '
>>> favorite_language = favorite_language.rstrip()
>>> favorite_language
'python'
你还可以剔除字符串开头的空白,或同时剔除字符串两端的空白。为此,可分别使用方法lstrip() 和strip() 。
五.使用字符串时避免语法错误
message = "One of Python's strengths is its diverse community."
print(message)
撇号位于两个双引号之间,因此Python解释器能够正确地理解这个字符串
然而,如果你使用单引号,Python将无法正确地确定字符串的结束位置
message = 'One of Python's strengths is its diverse community.'
print(message)