一、给变量赋值字符串的时候,要用引号引起来,可以用单引号或者双引号;
1、输入:
message="hello world"
print(message)
输出:
hello world
2、输入:
message='hello world'
print(message)
输出:
hello world
注:这样可以方便的打印带引号的字符串;
3、输入:
message="cy said 'hello world'"
print(message)
输出:
cy said 'hello world'
4、输入:
message='cy said "hello world"'
print(message)
输出:
cy said "hello world"
二、修改字符串的大小写
(1). title() :把字符串中每个单词的首字母变为大写,其它置为小写
输入:
message='cy sAid "hello world"'
print(message.title())
输出:
Cy Said "Hello World"
注:message.title()中的.可以理解为要执行.后面的操作,而括号里则是一些附加的操作,不需要则为空;
(2).upper() : 把字符串全部变为大写
输入:
message='cy sAid "hello world"'
print(message.upper())
输出:
CY SAID "HELLO WORLD"
(3).lower() : 把字符串全部变为小写
输入:
message='cy sAid "hello world"'
print(message.lower())
输出:
cy said "hello world"
三、连接字符串:使用f"{ a }{ b }"
1、变量用 { } 括起来
输入:
first_string="hello"
second_string="world"
fina_string=f"{first_string}{second_string}"
print(fina_string)
输出:
helloworld
2、{ }之外的字符也会起作用,可以穿插在{ }与{ }之间,包括空格
输入:
first_string="hello"
second_string="world"
fina_string=f"Cy said {first_string} {second_string}"
print(fina_string)
输出:
Cy said hello world
四、制表符(\t)和换行符(\n)的妙用
输入:
print("Language:\n\tPython\n\tC\n\tJavascript")
输出:
Language:
Python
C
Javascript
五、删除字符串中的空白:Python 能够找出字符串开头和末尾多余的空白;
1、要确保字符串末尾没有空白,可使用.rstrip();
first_string="Python "
print(first_string.rstrip())
注:这种操作删除空白只是暂时的,要关系到变量才是永久的,一般这样做
first_string="Python "
first_string=first_string.rstrip()
print(first_string)
2、要确保字符串开头没有空白,可使用.lstrip();
first_string=" Python"
first_string=first_string.lstrip()
print(first_string)
3、要确保字符串开头没有空白,可使用.strip();
first_string=" Python "
first_string=first_string.strip()
print(first_string)