首页  >  文章  >  系统教程  >  python之字符串详解

python之字符串详解

王林
王林转载
2024-02-14 17:30:30941浏览

python之字符串详解

1,变量命名

C/C++标识符的命名规则:变量名只能包含字母、数字和下划线,并且不可以以数字打头。不可以使用C/C++的关键字和函数名作为变量名。

变量命名的规则和C/C++标识符的命名规则是类似的:变量名只能包含字母、数字和下划线,并且不可以以数字打头。不可以使用python的关键字和函数名作为变量名。

另外,我们在取名的时候,尽量做到见名知意(具有一定的描述性)。

2.python字符串

在python种,用引号括起来的都是字符串(可以是单引号,也可以是双引号)

虽然,字符串可以是单引号,也可以是双引号,但是如果出现混用,可能就会出错,如下例:

"I told my friend,'python is really useful' " #true
'I told my friend,"python is really useful" ' #true
'I told my friend,'python is really useful' '  #false

一般情况下,我们的集成开发环境会对于我们写的代码进行高亮显示的,应该写完之后根据颜色就可以看出来错误(但是不是所有人都能看出来的),如果没看出来,可以在编译的时候,发现报错如下:

SyntaxError: invalid syntax

这时候,我们就应该去检查一下,是不是在代码中引号混用等。

3,字符串方法总结
(1)每个单词的首字母大写的title()方法
str = "The best makeup is a smile."
print( str )
print( str.title() )
print( str )

输出如下:

The best makeup is a smile.
The Best Makeup Is A Smile.
The best makeup is a smile.

总结,通过这个例子,这可以看出来title()方法是暂时的,并没有更改原来字符串的值。

(2)将字符串变为全大写的upper()方法
str = "The best makeup is a smile."
print( str )
print( str.upper() )
print( str )

输出如下:

The best makeup is a smile.
THE BEST MAKEUP IS A SMILE.
The best makeup is a smile.

总结,通过这个例子,这可以看出来upper()方法是暂时的,并没有更改原来字符串的值。

(3)将字符串变为全小写的lower()方法
str = "The best makeup is a smile."
print( str )
print( str.lower() )
print( str )

输出如下:

The best makeup is a smile.
the best makeup is a smile.
The best makeup is a smile.

总结,通过这个例子,这可以看出来lower()方法是暂时的,并没有更改原来字符串的值。

(4)合并字符串

python使用“ + ”号来合并字符串。
例如:

str = "The best makeup is a smile."
print( "He said that "+str.lower() )

输出如下:

He said that the best makeup is a smile.
(5)删除字符串前端空白的lstrip()方法

例如:

str = "    The best makeup is a smile."
print( str )
print( str.lstrip() )
print( str )

输出如下:

    The best makeup is a smile.
The best makeup is a smile.
The best makeup is a smile.

总结,通过这个例子,这可以看出lstrip()方法是暂时的,并没有更改原来字符串的值。

(6)删除字符串后端空白的rstrip()方法

例如:

str = "    The best makeup is a smile.    "
print( str )
print( str.rstrip() )
print( str )

输出如下:

"    The best makeup is a smile.    "
"    The best makeup is a smile. "
"    The best makeup is a smile.    "

总结,通过这个例子,这可以看出rstrip()方法是暂时的,并没有更改原来字符串的值。

(7)删除字符串两端空白的strip()方法

例如:

str = "    The best makeup is a smile.    "
print( str )
print( str.strip() )
print( str )

输出如下:

" The best makeup is a smile. "
"The best makeup is a smile."
" The best makeup is a smile. "

总结,通过这个例子,这可以看出strip()方法是暂时的,并没有更改原来字符串的值。

看到这里,你估计想问,那我如何更改字符串的值呢?只需要将更改过后的值再写回原来的字符串就可以了。

下面我们来举一个例子:

str = "The best makeup is a smile."
print( str )
str = str.title()
print( str )

输出如下:

The best makeup is a smile.
The Best Makeup Is A Smile.

好啦,今天的字符串总结先到这里,如果有疑问,欢迎留言。

以上是python之字符串详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:linuxprobe.com。如有侵权,请联系admin@php.cn删除