Python实现空格后的字母变大写
时间: 2023-11-29 15:58:30 浏览: 35
可以使用Python内置的字符串方法`title()`实现空格后的字母变大写。`title()`方法会将每个单词的首字母大写。
例如,将字符串"hello world"中每个单词的首字母大写:
```python
string = "hello world"
new_string = string.title()
print(new_string)
```
输出结果为:
```
Hello World
```
如果想要只将第一个单词的首字母大写,可以使用`capitalize()`方法:
```python
string = "hello world"
new_string = string.capitalize()
print(new_string)
```
输出结果为:
```
Hello world
```
相关问题
首字母大写、过滤多余空格后输出
对于一段输入文本,可以使用以下Python代码实现首字母大写、过滤多余空格后输出:
```
text = input() # 获取输入文本
text = text.strip() # 去除首尾空格
text = ' '.join(text.split()) # 去除多余空格
text = text.lower() # 转换为小写
text = text.title() # 首字母大写
print(text) # 输出结果
```
该代码首先获取输入文本,使用`strip()`函数去除首尾空格,然后使用`split()`函数将文本按空格分割成单词,再使用`join()`函数将单词重新组合成文本,去除多余空格。接着将文本转换为小写,并使用`title()`函数将每个单词的首字母大写。最后输出结果。
例如,对于输入文本" hello world! ",该代码将输出"Hello World!"。
python中输出字符串中大写字母 小写字母 数字 空格的个数
可以使用循环遍历字符串中的每个字符,然后判断字符的类型并计数。具体代码如下:
```python
s = 'Hello World 123'
upper_count = 0
lower_count = 0
digit_count = 0
space_count = 0
for c in s:
if c.isupper():
upper_count += 1
elif c.islower():
lower_count += 1
elif c.isdigit():
digit_count += 1
elif c.isspace():
space_count += 1
print("大写字母个数:", upper_count)
print("小写字母个数:", lower_count)
print("数字个数:", digit_count)
print("空格个数:", space_count)
```
输出结果为:
```
大写字母个数: 2
小写字母个数: 8
数字个数: 3
空格个数: 2
```