1.字符串定義
字符串:以雙引號或單引號包圍的數據
2.字符串的拼接
練習:
a = 'hello'
b = 'world'
c = a + b
print(c)
運行結果:helloworld
3.字符串的查找方法
count |
計數功能,返回自定字符在字符串中的個數 |
find |
查找,返回從左第一個指定字符的索引,找不到返回-1 |
rfind |
查找,返回從右第一個指定字符的索引,找不到返回-1 |
index |
查找,返回從左附一個指定字符的索引,找不到報錯 |
rindex |
查找,返回從右第一個指定字符的索引,找不到報錯 |
Count:
test = 'hello world'
print(test.count('o'))
運行結果:2
Find:
test = 'hello world'
print(test.find('world'))
運行結果:6
test = 'hello world'
print(test.find('word'))
運行結果:-1
rfind:
test = 'hello world'
print(test.rfind('world'))
運行結果:6
test = 'hello world'
print(test.rfind('word'))
運行結果:-1
Index:
test = 'hello world'
print(test.index ('o'))
運行結果:4
test = 'hello world'
print(test.index ('q'))
運行結果:ValueError: substring not found
Rindex:
test = 'hello world'
print(test.rindex ('o'))
運行結果:7
4.字符串的分割
partition |
把字符串從指定位置分成三部分,從左開始 的第一個字符 |
rpartition |
類似partition,從右開始 |
splitlines |
識別每行的\n併合並且分割輸出 |
Partition:
test = 'hello world'
print(test.partition('o'))
運行結果:('hell', 'o', ' world')
rpartition:
test = 'hello world'
print(test.rpartition('o'))
運行結果:('hello w', 'o', 'rld')
Splitlines:
test = 'hello\nworld'
print (test)
print(test.splitlines())
運行結果:hello
world
['hello', 'world']
5.字符串的替換
replace:
test = 'hello world'
print (test)
print(test.replace('o','x'))
運行結果:hello world
hellx wxrld
作者:QinL