字符串就是一系列字符。在Python中,用引号括起来的都是字符串,其中的引号可以是单引号,也可以是双引号,如下所示:
'This is a string.'
"This is also a string."
这种灵活性让你能够在字符串中包含引号和撇号:
‘I told my friend , “Python is my favorite language!”’
“The language ‘Python’ is named after Monty Python,not the snake.”
“One of Python’s strengths is its diverse and supportive community.”
字符串大小写
message = "hello python!"
# 原始字符串
print(message)
# 单词首字母大写
print(message.title())
# 全部大写
print(message.upper())
# 全部小写
print(message.lower())
程序运行输出
hello python!
Hello Python!
HELLO PYTHON!
hello python!
合并(拼接)字符串
可以用+号连接
first_name = "Bill"
last_name = "Gates"
print(first_name + " " + last_name)
程序运行输出
Bill Gates
删除空白
language = " Python "
# 去掉左边空格
print(language.lstrip())
# 去掉右边空格
print(language.rstrip())
# 去掉左右两边空格
print(language.strip())
程序运行输出
Python
Python
Python