python中字串支援的運算子及使用方法

2021-10-12 01:14:38 字數 2465 閱讀 3242

在python中,字串可以使用以下運算子:+*

innot in

isis not

==!=

使用方法舉例:

『+』 運算子,拼接字串的作用

s1 =

'hello'

s2 =

'world'

print

(s1+s2)

執行結果:

『*』 運算子,字串的倍數

s1 =

'a'*

5print

(s1)

執行結果:

in 運算子,判斷是否在字串中,返回布林型別 true或false

s1 =

'hello world!'

result =

'w'in s1

print

(result)

執行結果:

not in 運算子,判斷是否不在字串,返回布林型別 false或true

s1 =

'hello world!'

result =

'w'not

in s1

print

(result)

執行結果:

is 運算子,判斷字串位址是否相同,返回布林型別 true或false

s1 =

'hello world!'

s2 =

'hello world!'

result = s1 is s2

print

(result)

執行結果:

is not 運算子,判斷字串位址是否相同,返回布林型別 false或true

s1 =

'hello world!'

s2 =

'hello world!'

result = s1 is

not s2

print

(result)

執行結果:

== 運算子,判斷字串是否相等,返回布林型別 true或false

s1 =

'hello world!'

s2 =

'hello world!'

result = s1 == s2

print

(result)

執行結果:

!= 運算子,判斷字串是否相等,返回布林型別 false或true

s1 =

'hello world!'

s2 =

'hello world!'

result = s1 != s2

print

(result)

執行結果:

python字串運算 Python中的字串運算

上次說到 python 的字串,當然除了一些字串的概念呢,比較常用的就是字串的運算了,我們都見過數字的運算,其實字串的運算也不複雜。跟數字一樣,字串也可以進行加法運算以及乘法運算 需要提醒的是字串與字串是不能相乘的,會報錯 具體的表現形式就如圖所示。除此之外,我們還可以通過以下方式獲取字串中的單個字...

Python字串運算

下表例項變數a值為字串 hello b變數值為 python 操作符描述例項 字串連線 a b 輸出結果 hellopython 重複輸出字串 a 2 輸出結果 hellohello 通過索引獲取字串中字元 a 1 輸出結果e 擷取字串中的一部分 a 1 4 輸出結果ell in成員運算子 如果字串...

Python 字串運算 大全

1 字串拼接str 1 abcd str 2 efgh str 3 str 1 str 2 print str 3 abcdefgh 2 字串大小寫 1 大寫 str 1 abcd print str 1.upper abcd 2 小寫 str 1 abcd print str 1.lower ab...