53 lines
1.3 KiB
Python
53 lines
1.3 KiB
Python
# 1. 反转字符串
|
|
s = "hello"
|
|
reversed_s = s[::-1]
|
|
print(reversed_s) # 输出: "olleh"
|
|
|
|
# 2. 判断是否是回文
|
|
s = "racecar"
|
|
is_palindrome = s == s[::-1]
|
|
print(is_palindrome) # 输出: True
|
|
|
|
# 3. 统计某个字符的出现次数
|
|
s = "hello"
|
|
char_count = s.count("l")
|
|
print(char_count) # 输出: 2
|
|
|
|
# 4. 删除字符串中的元音
|
|
s = "beautiful"
|
|
vowels = "aeiouAEIOU"
|
|
new_s = ''.join(c for c in s if c not in vowels)
|
|
print(new_s) # 输出: "btfl"
|
|
|
|
# 5. 计算字符串中的单词数量
|
|
s = "I love Python"
|
|
word_count = len(s.split())
|
|
print(word_count) # 输出: 3
|
|
|
|
# 6. 检查字符串是否只包含字母
|
|
s = "Python123"
|
|
only_alpha = s.isalpha()
|
|
print(only_alpha) # 输出: False
|
|
|
|
# 7. 字符串大小写转换
|
|
s = "Hello World"
|
|
swapped_s = s.swapcase()
|
|
print(swapped_s) # 输出: "hELLO wORLD"
|
|
|
|
# 8. 删除字符串中的重复字符(保留首次出现的顺序)
|
|
s = "banana"
|
|
seen = set()
|
|
new_s = ''.join(seen.add(c) or c for c in s if c not in seen)
|
|
print(new_s) # 输出: "ban"
|
|
|
|
# 9. 获取字符串中第一个不重复的字符
|
|
s = "swiss"
|
|
for c in s:
|
|
if s.count(c) == 1:
|
|
print(c) # 输出: "w"
|
|
break
|
|
|
|
# 10. 反转字符串中的单词
|
|
s = "I love Python"
|
|
reversed_words = ' '.join(s.split()[::-1])
|
|
print(reversed_words) # 输出: "Python love I" |