如何ı在字符串中替换为随机数

发布于 2025-01-28 10:56:28 字数 282 浏览 1 评论 0原文

我试图将围墙更改为随机数,并且必须在Phyton Ex中的(0,9)之间。 “ Hello world”到“ Hello6world”或“ı是国王”到“ı5am6the8King”

import random
text = input("Text :")
text.replace(" ", str((random.randint(0, 9))))
print(text)

这是我的代码,但并没有将空白变为数字。

I am trying to change whitespaces to random number and number must be between the (0,9) in phyton ex. "hello world" to "hello6world" or "ı am the king" to "ı5am6the8king"

import random
text = input("Text :")
text.replace(" ", str((random.randint(0, 9))))
print(text)

here's my code but it didn't change the whitespace to number.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

恰似旧人归 2025-02-04 10:56:28
text = input("Text :")
print(text.replace(" ", str((random.randint(0, 9)))))

以上代码打印了使用的替换查询,因为它将打印返回的值
text.replace()自动。

如果您print(text)与原始代码中一样,它将打印在变量text中的原始字符串,因为字符串是不可变的。相反,您还可以将text.replace保存(“”,str((random.randint(0,9))))在其他变量中(让x),然后打印(x)

直接打印替换查询或将其保存在不同的变量中,然后打印它将解决用整数填充空格的问题。

*尽管这仅适用于所有白色空间生成的相同随机数

import random
text = input("Text :")
x=""
for i in range(len(text)):
    if text[i]==" ":
        x+=str((random.randint(0, 9)))
    else:
        x+=text[i]
print(x)

这将打印出一个替换为“ i8am7theking”的随机数,而不是“ i2am2the2king”的字符串。

text = input("Text :")
print(text.replace(" ", str((random.randint(0, 9)))))

The above code prints the replace query used as it will print the returned value of
Text.replace()automatically.

If you print(Text) as in original code it will print the original string saved in the variable Text as strings are immutable. Instead you can also save text.replace(" ", str((random.randint(0, 9)))) in a different variable (let x) and then print(x).

Either directly printing the replace query or saving it in a different variable and printing it will solve the issue of filling whitespaces with integer.

*Though this will apply only the same random number generated to all the whitespaces such as making the string as "i5am5the5king" instead of "i5am6the8king".You can rectify this by traversing the string and assigning whitespaces as a randint to a new string by doing

import random
text = input("Text :")
x=""
for i in range(len(text)):
    if text[i]==" ":
        x+=str((random.randint(0, 9)))
    else:
        x+=text[i]
print(x)

This will print a string with whitespaces replaced as random numbers such as "i8am7the9king" instead of "i2am2the2king".

美人迟暮 2025-02-04 10:56:28
For letter in myString: 
  If letter = ' ':
    #Replace with random
For letter in myString: 
  If letter = ' ':
    #Replace with random
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文