专业编程基础技术教程

网站首页 > 基础教程 正文

Python 中字符串和字符串处理的综合指南

ccvgpt 2024-09-08 12:46:02 基础教程 12 ℃

· Python 是一种通用且功能强大的编程语言,以其简单性和易用性而闻名。Python 中的基本数据类型之一是字符串,它表示字符序列。字符串在各种编程任务中起着至关重要的作用,例如处理文本数据、格式化输出和操作数据。/2.Stringhandling.py at main ·PytechAcademy/Python-基础

字符串的长度:Python 中的函数len()允许确定字符串的长度,即它包含的字符数。

Python 中字符串和字符串处理的综合指南

String = 'Hello, World'
print(len(String))  # Output: 12

索引:Python 字符串的第一个字符的索引为 0,第二个字符的索引为 1,依此类推。可以使用索引访问单个字符。

print(String[4])    # Output: o
print(String[-3])   # Output: r

切片:切片允许通过指定起始和结束索引从给定字符串中提取子字符串。如果省略起始索引,它将从字符串的开头开始。如果省略结束索引,它将一直到字符串的末尾。

print(String[3:])   # Output: lo, World

替换子字符串:可以使用方法replace()替换字符串中出现的子字符串

String_modified = String.replace('e', 'a')
print(String_modified)  # Output: Hallo, World

转换字符串大小写: Python 提供了多种方法来更改字符串的大小写,例如将其转换为大写、小写或将第一个字符大写。

print(String.upper())       # Output: HELLO, WORLD
print(String.lower())       # Output: hello, world
print(String.capitalize())  # Output: Hello, world

拆分字符串:方法split()用于根据分隔符将字符串拆分为子字符串列表。如果未指定分隔符,则按空格拆分。

Names = "A,G,J,M"
List_names = Names.split(',')
print(List_names)           # Output: ['A', 'G', 'J', 'M']
print(String.split())       # Output: ['Hello,', 'World']

字符串连接:连接允许将多个字符串合并为一个字符串。

a = 'hello'
b = 'world'
print(a + b)                # Output: helloworld

成员资格测试:可以使用关键字in检查字符串中是否存在子字符串。

print('c' in String)        # Output: False

使用条件语句进行成员资格测试:可以在语句中使用关键字if in来有条件地执行代码。

if 'c' in String:
    print('c is part of the string')
else:
    print('C is not part of the string')  # Output: C is not part of the string

字符串剥离:方法strip()用于从字符串中删除前导和尾随空格。如果只想删除前导空格或尾随空格,则可以分别使用lstrip()rstrip()

String_with_spaces = "   Hello, World   "
print(String_with_spaces.strip())    # Output: 'Hello, World'

字符串格式(f-strings):Python 提供了一种使用 f-strings(格式化字符串文字)格式化字符串的便捷方法。可以将表达式嵌入到字符串的大括号内{}

name = "John"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)   # Output: 'My name is John and I am 30 years old.'

字符串联接:方法join()用于将字符串列表连接成具有指定分隔符的单个字符串。

words = ["Hello", "World", "Python"]
delimiter = " "
joined_string = delimiter.join(words)
print(joined_string)      # Output: 'Hello World Python'

字符串填充ljust()rjust()方法分别用于左对齐和右对齐字符串。您可以指定生成的字符串的宽度和用于填充的字符。

text = "Python"
left_padded = text.ljust(10, '-')    # Output: 'Python----'
right_padded = text.rjust(10, '=')   # Output: '====Python'

字符串检查(is X 方法):Python 提供了多种方法isX,可用于检查字符串是否满足特定条件。一些常用的方法包括 isalpha()isdigit()isalnum()isspace()i slower()isupper() 等。

print('Hello'.isalpha())    # Output: True
print('123'.isdigit())      # Output: True
print('Hello123'.isalnum()) # Output: True
print('   '.isspace())      # Output: True
print('hello'.islower())    # Output: True
print('WORLD'.isupper())    # Output: True

字符串格式设置(format() 方法):format()方法允许您用占位符{}来设置字符串的格式,这些占位符将替换为作为方法参数提供的值。

name = "Alice"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)   # Output: 'My name is Alice and I am 25 years old.

最近发表
标签列表