字符串是一种在编程中常用的数据类型,用于表示文本数据。在 Python 中,字符串是不可变的序列,可以包含字母、数字、符号等字符。Python 允许使用单引号 (') 或双引号 (") 来创建字符串。
strOne = 'string'
strTwo = "string"
print(type(strOne), type(strTwo)) # <class 'str'> <class 'str'>
如果字符串中包含引号,应当确保字符串中使用一种引号,而在外部使用另一种引号,否则将会出现错误。
# 串中有单引号,使用双引号表示字符串
s1 = "I'm writing an article."
# 串中有双引号,使用单引号表示字符串
s2 = 'Tom said, "The weather is lovely today."'
name = 'Stan'
code = '23'
newstr = name+code # newstr = 'Stan23'
s = 'stan'
another = s*2 # another = 'stanstan'
s1 = "I'm writing an article."
print(s1[0]) # 输出'I'
print(s1[0:1:2]) # 输出'I'
# 切片不能用来改变原字符串的值
s1[0:3] = 'You are' # 将会报错
str.find(substr, startIndex, endIndex)
s = 'i is a variable.'
substr = 'a'
i = s.find(substr) # i = 5
print(type(i)) # <class 'int'>
string.count(substring, start, end)
s = 'i is a variable.'
substr = 'a'
i = s.count(substr) # i = 3
j = s.count('f') # j = 0
print(type(i)) # <class 'int'>
通常使用len()函数求字符串的长度
syntax:
len(object)
s = 'i is a variable.'
print(len(s)) # 16
s = 'Tom said, "The weather is lovely today,\n and I\'m planning to go for a walk in the park."'
print(s)
# 运行结果:
# Tom said, "The weather is lovely today,
# and I'm planning to go for a walk in the park."
i = int("12") # i = 12
j = float("23.0") # j = 23.0
s = str(i) # s = "12"
需要注意,用字符串表示的浮点数不能直接转成整型,但用字符串表示的整型可以直接转成浮点数(大范围不能推小范围,小范围可以推大范围)