I have an input string with Special characters: input= "the: sky is sunny" expected output = "sunny: is sky the"
Need to reverse a string words but preserving special char in string.
I have done simple string reverse, but that did not preserve the special characters :( Please help how to do this ? Thanks in advance.
Use re
:
s1 = 'the: sky is sunny'
fmt = re.sub(r'\w+', '{}', s1)
s2 = fmt.format(*reversed(re.findall(r'\w+', s1)))
>>> s2
'sunny: is sky the'
Regex: \\w+
\\w
: matches any word character (equivalent to [a-zA-Z0-9_])
+
: matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
Source: https://regex101.com/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.