字符串

字符串

Python3中的字符串可以使用双引号或者单引号括起来表示,如果需要输出的字符串里面出现引号,可以使用 \ 转义来去除引号的特殊作用,也可以用不同于外层的引号,例如双引号包单引号,单引号包双引号。三引号可以换行,可以用 + 连接不同的字符串。

#!/usr/bin/env python

str1 = "Hello"
str2 ='World'
str3 = 'Hello,\'World\''
str4 = "Hello,'World'"
str5 ='Hello,"World"'
str6 = """
Hello
World
"""

print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
print(str6)

print(str1 + str2)

运行结果

┌──(root㉿kali)-[~/python_code/python_1]
└─# python string.py
Hello
World
Hello,'World'
Hello,'World'
Hello,"World"

Hello
World

HelloWorld

字符串常用方法

  1. count:统计某字符出现的次数
  2. strip:默认去除首尾空白符(空格,换行符等)
  3. split:默认以空格进行分割,返回列表对象
  4. upperlower:大小写转换
  5. __len__():查看元素长度

注意点:字符串是不可变对象,这些方法会生成新的字符串,原来的不变。

Python 3.12.7 (main, Nov  8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> str1 = "aaaabbbbbbbcccccccc"
>>> str1.count('a')
4
>>> str1.count('b')
7
>>> str1.count('c')
8
>>>
>>> str2 = '    Python  \n'
>>> str2.strip()
'Python'
>>> str3 = 'aaaaPythonbbbb'
>>> str3.strip('a')
'Pythonbbbb'
>>> str3.strip('b')
'aaaaPython'
>>>
>>> str4 = 'Hello World'
>>> str4.spilt()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'spilt'. Did you mean: 'split'?
>>> str4.split()
['Hello', 'World']
>>> str5 = 'Hello:World'
>>> str5.split(':')
['Hello', 'World']
>>>
>>> str6 = "ILOVEyou"
>>> str6.upper()
'ILOVEYOU'
>>> str6.lower()
'iloveyou'
>>>
>>> len(str6)
8
>>> str6.__len__
<method-wrapper '__len__' of str object at 0x7fc0087e05f0>
>>> str6.__len__()
8
>>>
posted on 2025-06-15 17:31  burgess0x  阅读(15)  评论(0)    收藏  举报