温馨提示×

python str的用法是什么

小亿
82
2024-09-05 10:32:13
栏目: 编程语言

str 是 Python 中的一个内置类型,表示字符串。在 Python 中,字符串是由字符组成的序列,可以用单引号、双引号或三引号表示。

以下是 str 类型的一些常见用法:

  1. 创建字符串

使用单引号、双引号或三引号创建字符串:

s1 = 'hello'
s2 = "world"
s3 = '''This is a multiline
string.'''
  1. 字符串拼接

使用 + 运算符将两个字符串拼接在一起:

result = s1 + ' ' + s2
print(result)  # 输出:hello world
  1. 字符串重复

使用 * 运算符重复字符串:

repeated_str = s1 * 3
print(repeated_str)  # 输出:hellohellohello
  1. 字符串索引和切片

使用索引访问字符串中的特定字符,或者使用切片获取子字符串:

first_char = s1[0]  # 输出:h
sub_str = s1[1:4]  # 输出:ell
  1. 字符串长度

使用 len() 函数获取字符串的长度:

length = len(s1)
print(length)  # 输出:5
  1. 字符串方法

Python 中的字符串提供了许多有用的方法,如 upper(), lower(), replace(), split() 等:

upper_str = s1.upper()  # 输出:HELLO
lower_str = s2.lower()  # 输出:world
replaced_str = s1.replace('l', 'L')  # 输出:heLLo
split_str = s1.split('e')  # 输出:['h', 'llo']

这只是 str 类型的一些基本用法,更多信息可以参考 Python 官方文档

0