python字符串操作练习
时间: 2023-10-04 10:03:10 浏览: 126
python字符串操作
Python字符串操作练习题可以包括判断回文字符串、反转字符串、字符串变形(字母大小写切换)以及找到最长回文子串等任务。下面是几个例子:
1. 判断回文字符串(双指针):
```python
class Solution:
def judge(self, s: str) -> bool:
left = 0
right = len(s) - 1
while left < right:
if s[left != s[right]:
return False
left += 1
right -= 1
return True
```
2. 反转字符串:
```python
class Solution:
def reverse(self, s: str) -> str:
return s[::-1]
```
3. 字符串变形(字母大小写切换):
```python
class Solution:
def transform(self, s: str) -> str:
transformed = ""
for char in s:
if char.islower():
transformed += char.upper()
elif char.isupper():
transformed += char.lower()
else:
transformed += char
return transformed
```
4. 找到最长回文子串:
```python
class Solution:
def longestPalindrome(self, s: str) -> str:
longest = ""
for i in range(len(s)):
for j in range(len(s), i, -1):
substring = s[i:j]
if substring == substring[::-1 and len(substring) > len(longest):
longest = substring
return longest
```
阅读全文