导读 大多数人学习的第一门编程语言是C/C++,个人觉得C/C++也许是小白入门的最合适的语言,但是必须承认C/C++确实有的地方难以理解,初学者如果没有正确理解,就可能会在使用指针等变量时候变得越来越困惑,进而减少对于编程的兴趣,但是不可否认,一个程序员对于语言的深入理解是必备技能。学习过C/C++的同学转写python会很容易理解里面的规则,从而使得代码更加高效,优雅。下面我们总结一下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.

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

原文来自:http://www.cnblogs.com/wongyi/p/7843364.html

本文地址:https://www.linuxprobe.com/python-str.html编辑:王毅,审核员:逄增宝

本文原创地址:https://www.linuxprobe.com/python-str.html编辑:王毅,审核员:暂无