【发布时间】:2023-04-09 00:54:01
【问题描述】:
我正在尝试在字符串中查找大写首字母缩略词。例如,如果输入是“我需要尽快见到你,因为 YOLO,你知道”应该返回 ["ASAP", "YOLO"]。
#!/usr/bin/env python3
import string
def acronyms(s):
s.translate(string.punctuation)
for i, x in enumerate(s):
while x.upper():
print(x)
i += 1
def main():
print(acronyms("""I need to see you ASAP, because YOLO, you know."""))
if __name__ == "__main__":
main()
我试图去掉标点符号,然后循环遍历字符串,当它是大写时打印出字母。它导致了一个无限循环。我想使用字符串操作来解决这个问题,所以没有 RegEx
编辑:
- 为了提高效率而删除标点符号的变化
发件人:
exclude = set(string.punctuation)
s = "".join(ch for ch in s if ch not in exclude)
收件人:
s.translate(string.punctuation)
【问题讨论】:
标签: python string loops uppercase