开始使用免费开始使用

使用方法操作字符串

方法是附着在对象上的特殊函数。某些数据类型带有便于操作数据的方法。例如,.upper() 方法会返回字符串变量的全大写版本;.lower() 方法会返回字符串的全小写版本。

city = 'New York'
print(city.lower())

new york

另一个对字符串非常有用的方法是 .format(),它会用传入的参数替换字符串中的花括号。

city = 'New York'
print("City: {}".format(city))

City: New York

练习使用这些方法来操作字符串变量,同时顺便了解一个有趣的美国历史小知识!

本练习是课程的一部分

面向 MATLAB 用户的 Python

查看课程

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Print the lowercase version of this Jeopardy clue
clue = 'Signer of the Dec. of Indep., framer of the Constitution of Mass., second President of the United States'

print(clue.____)
编辑并运行代码