没有反向功能的反向字符串[重复]
Posted
技术标签:
【中文标题】没有反向功能的反向字符串[重复]【英文标题】:Reverse string without reverse function [duplicate] 【发布时间】:2017-04-10 08:49:10 【问题描述】:对于输入文本,我必须计算所有元音,将每个单词中的第一个字母大写并反向输出文本(不必大写),而不使用标题或反向函数。我能够算出元音的计数,但与其他两个比较困难。
def main():
vowelCount = 0
text = 'abc'
while(len(text) != 0):
text = input('Please etner some text or press <ENTER> to exit: ')
for char in text:
if char in 'aeiouAEIOU':
vowelCount += 1
print('Vowels:', vowelCount)
vowelCount = 0
for i in text:
i = text.find('') + 1
print(i)
print(text[0].upper() + text[1:])
main()
【问题讨论】:
单词倒序还是每个字符倒序? Reversing a string is already covered in great detail. 【参考方案1】:这里有两个反转字符串的例子。 切片字符串
>>> s = 'hello'
>>> reversed_s = s[::-1]
或者使用循环。
res = ''
for char in s:
res = char + res
完整代码
def main():
# Run infinitely until break or return
# it's more elegant to do a while loop this way with a condition to
# break instead of setting an initial variable with random value.
while True:
text = input('Please enter some text or press <ENTER> to exit: ')
# if nothing is entered then break
if not text:
break
vowelCount = 0
res = ''
prev_letter = None
for char in text:
if char.lower() in 'aeiou':
vowelCount += 1
# If previous letter was a space or it is the first letter
# then capitalise it.
if prev_letter == ' ' or prev_letter is None:
char = char.upper()
res += char # add char to result string
prev_letter = char # update prev_letter
print(res) # capitalised string
print(res[::-1]) # reverse the string
print('Vowel Count is: 0'.format(vowelCount))
# Example
Please enter some text or press <ENTER> to exit: hello world!
Hello World!
!dlroW olleH
Vowel Count is: 3
【讨论】:
感谢提示,但是如何在不反转字符串的情况下使用循环将每个单词大写。 @MrG 更新了答案。我已将其拆分,因此生成的字符串不会反向构造,而是使用建议的第一种方法(切片)在末尾反转以上是关于没有反向功能的反向字符串[重复]的主要内容,如果未能解决你的问题,请参考以下文章