字符串
- 字符串是以單引號或雙引號括起來的任意文本,例 ‘abc’、”def”。
- 字符串是不可變的。
創建字符串:
str1 = "hello world"
字符串運算:
字符串比較大小:
- 從第一個字符開始比較,誰的ASCII值大誰就大,如果相等會比較下個字符的ASCII值的大小。
字符串連接:
str1 = "you are a "
str2 = "good boy"
str3 = str1 + str2
print("str3 =", str3)
輸出重複字符串:
str1 = "good boy "
str2 = str1 * 3
print("str3 =", str2)
訪問字符串中的某一個字符:
str1 = "you are a good boy "
print(str1[10])
str1[10] = "a"
print("str1 =", str1)
'''
結果爲:
File "Q:/pycharm_project/stringDemo.py", line 4, in <module>
str1[10] = "a"
TypeError: 'str' object does not support item assignment
證明:字符串是不可變的。
'''
截取字符串:
str1 = "you are a good boy"
str2 = str1[10:15]
print("str2 =", str2)
str3 = str1[:15]
print("str3 =", str3)
str4 = str1[15:]
print("str4 =", str4)
str5 = str1[15:25]
print("str5 =", str5)
'''
結果爲:
str2 = good
str3 = you are a good
str4 = boy
str5 = boy
'''
判斷字符串包含關係:
str1 = "you are a good boy"
print("good" in str1)
print("good1" in str1)
print("good" not in str1)
print("good1" not in str1)
'''
結果爲:
True
False
False
True
'''
格式化輸出:
str1 = "you are a good boy"
num = 10
f1 = 7.8888888
print("str1 =", str1)
print("num =", num)
print("num =", num, "str1 =", str1)
print("num = %d, str1 = %s, f1 = %f" % (num, str1, f1))
print("num = %d, str1 = %s, f1 = %.3f" % (num, str1, f1))
'''
結果爲:
str1 = you are a good boy
num = 10
num = 10 str1 = you are a good boy
num = 10, str1 = you are a good boy, f1 = 7.888889
num = 10, str1 = you are a good boy, f1 = 7.889
'''