我将如何单独反转每个单词而不是整个字符串
How would I reverse each word individually rather than the whole string as a whole
我正在尝试单独反转字符串中的单词,因此单词仍然按顺序排列,但只是反转,例如 "hi my name is" 输出 "ih ym eman si" 但是整个字符串被翻转
r = 0
def readReverse(): #creates the function
start = default_timer() #initiates a timer
r = len(n.split()) #n is the users input
if len(n) == 0:
return n
else:
return n[0] + readReverse(n[::-1])
duration = default_timer() - start
print(str(r) + " with a runtime of " + str(duration))
print(readReverse(n))
首先用正则表达式将字符串拆分成单词、标点和空格similar to this。然后你可以使用生成器表达式单独反转每个单词,最后将它们与 str.join
.
连接在一起
import re
text = "Hello, I'm a string!"
split_text = re.findall(r"[\w']+|[^\w]", text)
reversed_text = ''.join(word[::-1] for word in split_text)
print(reversed_text)
输出:
olleH, m'I a gnirts!
如果你想忽略标点符号,你可以省略正则表达式,只拆分字符串:
text = "Hello, I'm a string!"
reversed_text = ' '.join(word[::-1] for word in text.split())
但是,逗号、感叹号等将成为单词的一部分。
,olleH m'I a !gnirts
这是递归版本:
def read_reverse(text):
idx = text.find(' ') # Find index of next space character.
if idx == -1: # No more spaces left.
return text[::-1]
else: # Split off the first word and reverse it and recurse.
return text[:idx][::-1] + ' ' + read_reverse(text[idx+1:])
我正在尝试单独反转字符串中的单词,因此单词仍然按顺序排列,但只是反转,例如 "hi my name is" 输出 "ih ym eman si" 但是整个字符串被翻转
r = 0
def readReverse(): #creates the function
start = default_timer() #initiates a timer
r = len(n.split()) #n is the users input
if len(n) == 0:
return n
else:
return n[0] + readReverse(n[::-1])
duration = default_timer() - start
print(str(r) + " with a runtime of " + str(duration))
print(readReverse(n))
首先用正则表达式将字符串拆分成单词、标点和空格similar to this。然后你可以使用生成器表达式单独反转每个单词,最后将它们与 str.join
.
import re
text = "Hello, I'm a string!"
split_text = re.findall(r"[\w']+|[^\w]", text)
reversed_text = ''.join(word[::-1] for word in split_text)
print(reversed_text)
输出:
olleH, m'I a gnirts!
如果你想忽略标点符号,你可以省略正则表达式,只拆分字符串:
text = "Hello, I'm a string!"
reversed_text = ' '.join(word[::-1] for word in text.split())
但是,逗号、感叹号等将成为单词的一部分。
,olleH m'I a !gnirts
这是递归版本:
def read_reverse(text):
idx = text.find(' ') # Find index of next space character.
if idx == -1: # No more spaces left.
return text[::-1]
else: # Split off the first word and reverse it and recurse.
return text[:idx][::-1] + ' ' + read_reverse(text[idx+1:])