Python 字符串操作:反转、回文判断、字符计数
Python 字符串操作:反转、回文判断、字符计数
本文将介绍三个用 Python 代码实现的字符串操作:反转字符串、判断回文和统计字符出现次数。
1. 反转字符串
该函数将输入字符串反转,例如输入 "Hello, world!",函数将返回 "!dlrow ,olleH"。
def reverse_string(s):
reversed_str = ""
for i in range(len(s)-1, -1, -1):
reversed_str += s[i]
return reversed_str
input_str = "Hello, world!"
print(reverse_string(input_str))
2. 判断回文
该函数判断给定字符串是否是回文。回文是指正向和反向拼写都是一样的字符串,例如 "level" 是回文,而 "hello" 不是。
def is_palindrome(s):
reversed_str = ""
for i in range(len(s)-1, -1, -1):
reversed_str += s[i]
return s == reversed_str
input_str = "level"
print(is_palindrome(input_str))
3. 计算字符出现次数
该函数计算给定字符串中每个字符出现的次数,并以字典的形式返回结果。例如,对于字符串 "hello",函数将返回 {'h': 1, 'e': 1, 'l': 2, 'o': 1}。
def count_characters(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count
input_str = "hello"
print(count_characters(input_str))
以上代码示例展示了三种基本字符串操作,通过学习这些代码可以帮助读者更好地理解字符串处理的基本方法。
原文地址: https://www.cveoy.top/t/topic/pOmV 著作权归作者所有。请勿转载和采集!