Python中字符串的操作

一、字符串操作

字符串连接

s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)  # Hello World

字符串重复

print("Ha" * 3)  # HaHaHa

字符串长度

s = "Python"
print(len(s))  # 6

二、字符串索引与切片

索引访问

s = "Python"
print(s[0])  # 'P' (第一个字符)
print(s[-1])  # 'n' (最后一个字符)

切片操作

s = "Python Programming"
print(s[0:6])    # 'Python' (索引0到5)
print(s[7:])     # 'Programming' (索引7到最后)
print(s[:6])     # 'Python' (开始到索引5)
print(s[::2])    # 'Pto rgamn' (步长为2)
print(s[::-1])   # 'gnimmargorP nohtyP' (反转字符串)

三、字符串方法

大小写转换

s = "Python"
print(s.upper())      # 'PYTHON'
print(s.lower())      # 'python'
print(s.capitalize()) # 'Python'
print(s.title())      # 'Python'

字符串替换

s = "Hello World"
print(s.replace("World", "Python"))  # Hello Python

字符串查找

s = "Hello World"
print(s.find("World"))    # 6 (返回索引)
print(s.index("World"))   # 6 (类似find但找不到会报错)
print("World" in s)       # True (成员检查)

字符串格式化

name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))

print("My name is {} and I'm {} years old.".format(name, age))
print("My name is {0} and I'm {1} years old. {0} is my first name.".format(name, age))

print(f"My name is {name} and I'm {age} years old.")
print(f"Next year I'll be {age + 1} years old.")

字符串分割与连接

s = "apple,banana,orange"
print(s.split(","))       # ['apple', 'banana', 'orange']

lst = ["Python", "is", "great"]
print(" ".join(lst))      # Python is great

字符串修剪

s = "   Python   "
print(s.strip())      # 'Python' (去除两端空白)
print(s.lstrip())     # 'Python   ' (去除左端空白)
print(s.rstrip())     # '   Python' (去除右端空白)

字符串验证

s = "Python123"
print(s.isalpha())      # False (是否全字母)
print(s.isalnum())      # True (是否字母或数字)
print(s.isdigit())      # False (是否全数字)
print(s.islower())      # False (是否全小写)
print(s.isupper())      # False (是否全大写)
print(s.isspace())      # False (是否全空白字符)
print(s.startswith("Py"))  # True
print(s.endswith("123"))   # True

你可能感兴趣的:(python,java,服务器)