首頁  >  文章  >  系統教程  >  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刪除