【问题标题】:Special characters to the end of sentence [closed]句末的特殊字符[关闭]
【发布时间】:2018-08-21 06:30:07
【问题描述】:

对于随机字符串如:

H!i I am f.rom G3?ermany

如何将所有特殊字符移到词尾,例如:

Hi! I am from. Germany3?

【问题讨论】:

  • 定义特殊字符。向我们展示你的所作所为。

标签: python character


【解决方案1】:

你可以试试这个:

s = "H!i I am f.rom G3?ermany"
l = []
for i in s.split():
    k = [j for j in i if j.isalpha()]
    for m in i:
        if not m.isalpha():
           k.append(m)
    l.append(''.join(k))
print(' '.join(l))

它会像这样运行:

"Hi! I am from. Germany3?

python 2x 中,您可以像这样在单行中完成:

k = ' '.join([filter(str.isalpha,i)+''.join([j for j in i if not j.isalpha()]) for i in s.split()])

【讨论】:

  • 这段代码令人憎恶...
【解决方案2】:

我将特殊字符定义为任何不是 a-z、A-Z 或空格的字符:

您可以将字符串拆分为单词,使用正则表达式查找每个单词中的特殊字符,删除它们,将它们添加回单词的末尾,然后将单词连接在一起以创建新字符串:

import re

string = "H!i I am f.rom G3?ermany"

words = string.split(' ')

pattern = re.compile('[^a-zA-Z\s]')

new = ' '.join([re.sub(pattern, '', w) + ''.join(pattern.findall(w)) for w in words])

这会将H!i I am f.rom G3?ermany 变成Hi! I am from. Germany3?

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 2014-04-02
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 2014-09-25
    • 2019-05-18
    相关资源
    最近更新 更多