-1

in a text file 0.txt, i have a line " shortens his length outside off, xxxx presses across and defends it to the off-side ". I am storing that data to list.


    file = io.open('./commentry/0.txt','r',encoding="utf8")
    for i in file.readlines():
        zeroComm.append(i)

Now i want to get that line from list and print it when and where required by passing variable to it. For example.

name = 'martian'
print(random.choice(zeroComm))

I need output like [name in place of xxxx] shortens his length outside off, martian presses across and defends it to the off-side

  • Does this answer your question? [How to use string.replace() in python 3.x](https://stackoverflow.com/questions/9452108/how-to-use-string-replace-in-python-3-x) – Tomerikoo Aug 05 '21 at 14:20

3 Answers3

0

Use str.replace. This replaces all instances of one substring with another substring in a larger string.

string = " shortens his length outside off, xxxx presses across and defends it to the off-side "
name = "martian"
print(string.replace("xxxx", name))

Docs here: https://docs.python.org/3/library/stdtypes.html#str.replace

EnderShadow8
  • 788
  • 6
  • 17
0

Is the part that should be replaced always 'xxxx' or on a well defined format? Then you could simply use yourstring.replace('xxxx', thename), or use regex sub function if you want to match a pattern and not an exact string.

Also, I'm not sure where these text files you are reading come from, but if you are generating them yourself you could instead of 'xxxx' insert '{name}' when you create them, and then use something like

print("Hello {name}".format(name='Martin'))

This would obviously not be a solution if you can't change the format of the text files.

Niklas
  • 21
  • 3
0

You can do like this.

change_name(s, name) - Accepts two strings - s and name, replaces xxxx with name and returns the replaced string.

Note that this doesn't change the original string.

You can use this function wherever you need by passing in the string s and name.

lst = [" shortens his length outside off, xxxx presses across and defends it to the off-side ."]

# Replaces xxxx with name passed to argument and returns the string.
def change_name(s, name):
    return s.replace('xxxx', name)

print(change_name(lst[0], 'martian'))
Ram
  • 4,724
  • 2
  • 14
  • 22