更改Python函数中的字符串 [英] Altering Strings in Python Functions

查看:41
本文介绍了更改Python函数中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个基本问题;我让用户调用一个需要输入字符串的函数例如,在这种情况下,可以说苹果.因此调用了函数get_viewget_view('apples')及其工作是将苹果中的所有字符转换为隐藏字符,例如'apples'->'^^^^^^'的例子,hello world将变为'^^^^^^ ^^^^^'等,我的问题是,在下面的代码中,它会转换所有字母和数字等,但不会在hello世界之间保留空白,并且也不会考虑(').我如何修改我的代码以使其完全起作用?

So i have a basic problem; I have the user call a function which takes a string input for example, lets say in this case apples. so the function, get_view, is called get_view('apples') and its job is to convert all characters in apples to hidden characters, example for 'apples'-->'^^^^^^', hello world would become '^^^^^ ^^^^^', and etc, my problem is that in my code below it does convert all letters and numbers and etc but it does not leave the empty space present between hello world, and it also does not consider ('). How can i modify my code to make it fully functional?

代码:

def get_view(puzzle):

    view = puzzle
    length = len(puzzle)
    for index in range(0,length):
        if ((puzzle[index]) != '' or '-' ):
            view = view[: index] + HIDDEN + view[index+1:]

HIDDEN ='^'(其常量)

HIDDEN = '^' (its a constant)

谢谢您,网站上的新人< 3

Thank you, new to the website <3

推荐答案

我使用 regex 函数,如 re.sub(),如下所示:

i use regex functions like re.sub() for most non-trivial string operations, like this:

import re
print(re.sub("[a-zA-Z0-9_']", "^", "Hello world, what's up?"))
#                                   ^^^^^ ^^^^^, ^^^^^^ ^^?

这篇关于更改Python函数中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆