字符串是 Python 语言中的一种数据类型,表示由字符组成的序列。常见的字符串操作包括比较、拼接、切割、转义字符等。以下是相关的函数和用法:
- s1 = "hello"
- s2 = "world"
- if s1 == s2:
- print("s1 和 s2 相等")
- else:
- print("s1 和 s2 不相等")
- s1 = "hello"
- s2 = "world"
- s3 = s1 + " " + s2
- print(s3) # 输出 "hello world"
- s = "hello,world"
- parts = s.split(",")
- print(parts) # 输出 ["hello", "world"]
- print("hello\nworld") # 输出
- hello
- world
-
- print("hello\tworld") # 输出
- hello world
- s = "hello,world"
- parts = s.split(",")
- print(parts) # 输出 ["hello", "world"]
- s = "hello,world"
- s = s.replace(",", " ")
- print(s) # 输出 "hello world"
- s = "hello,world"
- index = s.find("world")
- if index != -1:
- print("找到了,位置是", index)
- else:
- print("没找到")
- s = " hello world "
- s = s.strip()
- print(s) # 输出 "hello world"
- s = "Hello World"
- s1 = s.lower()
- s2 = s.upper()
- print(s1) # 输出 "hello world"
- print(s2) # 输出 "HELLO WORLD"