python编写代码,将英文字符串内容转化为大写,提取文件中首字母为大写“T”的单词,不允许重复。打印结果(每行打印一个单词)。“
时间: 2024-03-10 08:50:35 浏览: 17
假设英文字符串内容在一个文件中,可以按照行读取文件内容,然后对每一行进行处理。可以使用 `upper()` 方法将英文字符串转化为大写,然后使用 `split()` 方法将字符串按照空格分割为一个列表。接着可以使用列表推导式和 if 语句选出首字母为大写 'T' 的单词并去重,最后使用 for 循环输出结果。
以下是实现代码:
```python
with open('file.txt', 'r') as f:
for line in f:
words = line.upper().split()
selected_words = list(set([word for word in words if word.startswith('T')]))
for word in selected_words:
print(word)
```
其中 `file.txt` 是存储英文字符串内容的文件名,需要根据实际情况进行修改。
相关问题
python编写代码,提取字符串中首字母为大写“T”的单词,不允许重复。打印结果(每行打印一个单词)。
可以使用 `split()` 方法将字符串按照空格分割为一个列表。接着可以使用列表推导式和 if 语句选出首字母为大写 'T' 的单词并去重,最后使用 for 循环输出结果。
以下是实现代码:
```python
string = "This is a test string. There are many words starting with T in this string. Let's extract them!"
words = string.split()
selected_words = list(set([word for word in words if word.startswith('T') and word[0].isupper()]))
for word in selected_words:
print(word)
```
输出结果为:
```
Test
This
There
```
Python不使用内置函数如何将字符串中的小写字母转化为大写字母,将大写字母转化为小写字母
可以使用ASCII码进行转换。对于小写字母,其ASCII码是97~122,对应的大写字母的ASCII码是65~90。因此,可以通过判断每个字符的ASCII码来进行大小写转换。示例代码如下:
```python
def swap_case(s):
res = ''
for c in s:
if ord('a') <= ord(c) <= ord('z'): # 判断是否为小写字母
res += chr(ord(c) - 32) # 转换为大写字母
elif ord('A') <= ord(c) <= ord('Z'): # 判断是否为大写字母
res += chr(ord(c) + 32) # 转换为小写字母
else:
res += c # 非字母字符直接添加
return res
```
使用示例:
```python
s = 'Hello, World!'
print(swap_case(s)) # 输出:hELLO, wORLD!
```