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
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print("Hello, " + full_name.title() + "!")
# 输出:
Hello, Ada Lovelace!
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
message = "Hello, " + full_name.title() + "!"
print(message)
# 输出:
Hello, Ada Lovelace!
要在字符串中添加制表符
,可使用字符组合\t
,如下述代码的❶处所示:
>>> print("Python")
Python
>>> print("\tPython")
❶
Python
要在字符串中添加换行符
,可使用字符组合\n
:
>>> print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript
还可在同一个字符串中同时包含制表符和换行符。
字符串"\n\t
" 让Python换到下一行,并在下一行开头添加一个制表符
。
示例:如何使用一个单行字符串来生成四行输出:
>>> print("Languages:\n\tPython\n\tC\n\tJavaScript")
Languages:
Python
C
JavaScript
Python能够找出字符串开头和末尾多余的空白。要确保字符串末尾没有空白
,可使用方法rstrip()
。
>>> 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() :
>>> favorite_language = ' python '
>>> favorite_language.rstrip()
❷
' python'
>>> favorite_language.lstrip()
❸
'python '
>>> favorite_language.strip()
❹
'python'
在Python中,可对整数执行加(+ )减(- )乘(* )除(/ )运算。
>>> 2 + 3
5
>>> 3 - 2
1
>>> 2 * 3
6
>>> 3 / 2
1.5