# 定义一个字符串(在python中没有字符或字符串之分)
s = '112233'
print(s)
>>>112233
# 判断字符串是否包含某字符串
print('22' in s)
>>>True
print('24' in s)
>>> False
print(s.find('22'))
>>>2
print(s.find('24' in s))
>>>-1
# 统计一个字符串在另一个字符中出现的次数
s = '112233'
print(s.count('3'))
>>>2
print(s.count('33'))
>>>1
# 字符串首字母大写
s = 'username'
s = s.capitalize()
print(s)
>>>Username
# 将所有字母全部大写或小写
s = '12adefaewUee==iujea2'
s = s.upper()
print(s)
>>>12ADEFAEWUEE==IUJEA2
s = s.lower()
print(s)
>>>12adefaewuee#==iujea2
# 删除字符串左边/右边/左右空格
s = ' 123 '
s.lstrip()
>>>'123 '
s.rstrip()
>>>' 123'
s.strip()
>>>'123'
# 替换字符串的部分字符内容
s = '112233'
s.replace('2', 'b')
>>>11bb33
s.replace('22', 'b')
>>>11b33
# 将字符串分割成字符串数组
s = 'this is a book'
s.split(' ')
>>>['this', 'is', 'a', 'book']
# 判断字符串是否以某字符开头或结尾
s = '112233'
s.startswith('11')
>>>True
s.startswith('22')
>>>False
s.endswith('33')
>>>True
# 字符串的遍历
s = '12ad@@'
for each in s:
print(each)
>>>1
>>>2
>>>a
>>>d
>>>@
>>>@
python初入江湖:str字符串
最新推荐文章于 2023-06-18 17:23:09 发布