请编写代码,删除字符串前端的空白字符。
时间: 2024-03-06 22:51:46 浏览: 13
以下是 Python 代码示例:
```python
string_with_spaces = " Hello, World!"
string_without_spaces = string_with_spaces.lstrip()
print(string_without_spaces) # 输出 "Hello, World!"
```
这里使用了字符串的 `lstrip()` 方法,它可以删除字符串前端的空白字符(包括空格、制表符、换行符等)。
相关问题
请编写C语言代码,删除字符串前端的空白字符。
以下是 C 语言代码示例:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char string_with_spaces[] = " Hello, World!";
int i = 0;
while (isspace(string_with_spaces[i])) {
i++;
}
char *string_without_spaces = string_with_spaces + i;
printf("%s", string_without_spaces); // 输出 "Hello, World!"
return 0;
}
```
这里使用了 C 标准库中的 `isspace()` 函数来判断字符是否为空白字符(包括空格、制表符、换行符等),然后使用循环找到第一个非空白字符的位置,最后将指针指向该位置即可。
编写代码判断字符串是否回文
可以通过以下 Python 代码判断一个字符串是否回文:
```python
def is_palindrome(s):
return s == s[::-1]
# 调用函数判断字符串是否回文
s = "racecar"
print(is_palindrome(s)) # 输出 True
```
代码中,我们定义了一个函数 `is_palindrome(s)`,该函数接受一个字符串参数 `s`,并返回一个布尔值,表示该字符串是否回文。
在函数中,我们使用 Python 切片语法 `[::-1]` 来翻转字符串。如果原字符串等于翻转后的字符串,则返回 True,否则返回 False。
在主程序中,我们定义了一个字符串 `s`,并调用函数判断该字符串是否回文,输出结果为 True。