简体   繁体   中英

How do I change the location of a character in a sentence?

I'm trying to move a character from the beginning of a word to the end of that word.

For example:
input: _baba _dede
output baba_ dede_

How can I achieve that.

I tried this with re.sub()

import re
key="_baba _dede"
g=re.sub("_.","._",key)
print(g)
output;
._aba ._ede

But it is not working

a solution without regex

text = "_baba _dede"
print [word[1:] + word[0] for word in text.split()]

Using Regex. Pattern re.sub(r"_(\\w*)", r"\\1_", string)

Ex:

import re

s = "_baba _dede"
print(re.sub(r"_(\w*)", r"\1_", s))

Output:

baba_ dede_

You don't need a regex for this, just split the words, remove the underscore from front and put it in the back


key="_baba _dede"
li = [ item.replace('_','')+'_' for item in key.split()]
print(' '.join(li))

Output is

baba_ dede_

Or restructure the word to move the character in the front towards the back


key="_baba _dede"
li = [ item[1:] + item[0] for item in key.split()]
print(' '.join(li))

Output

baba_ dede_

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM