我将如何为输入的字符串制作标题大小写。有人告诉我我必须使用循环,并且不允许使用title函数。如果该字符作为字符串的第一个字符出现,或者紧随空格字符出现,或者紧随标点字符出现,则必须为大写字母
string = input("Enter a string")
acc = ""
for char in string:
if char in "'.,;:?! ":
char = string.upper()
acc += char
print(acc)
答案 0 :(得分:0)
~/.ssh/authorized_keys
答案 1 :(得分:0)
您可以检查每个字符是否必须使用大写字母:
string = input("Enter a string: ")
acc = ""
next_is_upper = True # the first character will be uppercase
for char in string:
if next_is_upper:
acc += char.upper()
else:
acc += char
next_is_upper = char in "'.,;:?! "
print(acc)
# Enter a string: this string, will:be titled
# This String, Will:Be Titled
答案 2 :(得分:0)
您发布的代码未引用字符邻接。您测试当前字符的标点符号...,然后尝试操纵那个字符。另外,请不要为变量指定与类型(字符串)相同的名称。
我们介绍一个布尔值(标志),它告诉我们何时即将发生大写事件。
str = "now is the time 12:57 p.m." # test string
punct = "'.,;:?! " # punctuation set
new = "" # output string
cap_next = True # Do I capitalize the next character?
for char in str:
if cap_next:
char = char.upper()
new += char
cap_next = char in punct
print(new)
输出:
Now Is The Time 12:57 P.M.
答案 3 :(得分:0)
string = input("Enter a string")
acc = ""
for n, char in enumerate(string):
if n == 0 and char.isalpha():
acc += char.upper()
elif n > 0 and char.isalpha() and string[n-1] in "'.,;:?! ":
acc += char.upper()
else:
acc += char
print(acc)
答案 4 :(得分:0)
这是解决您问题的一种方法。
string = ' '.join(word[0].upper() + word[1:] for word in string.split())