简体   繁体   中英

Removing '\n', [, and ] in python3

I'm writing a GUI that will generate a random names for taverns for some tabletop gameplay. I have .txt docs that have something like this.

Red
Green
Yellow
Resting
Young

And

King
Dragon
Horse
Salmon

I'm reading and randomly joining them together using the following

x = 1
tavern1 = open('tavnames1.txt', 'r')
name1 = tavern1.readlines()
tav1 = random.sample(name1, int(x))
tav1 = str(tav1)
tav1 =tav1.strip()
tav1 =tav1.replace('\n', '')


tavern2 = open('tavnames2.txt', 'r')
name2 = tavern2.readlines()
tav2 = random.sample(name2, int(x))
tav2 = str(tav2)


TavernName = 'The' + tav1 + tav2


print(TavernName)

The output I get will look something like

The['Young\n']['Salmon\n']

I've tried using .replace() and .strip() on the string but it doesn't seem to work.

Any ideas?

Cheers.

sample() always returns list - even if there is one element. And you use str() to convert list into string so Python adds [ ] , and strip() doesn't work because \\n is not at the end of string.

But you can use random.choice() which returns only one element - so you don't have to convert to string and you don't get [ ] . And then you can use strip() to remove \\n

tavern1 = open('tavnames1.txt')
name1 = tavern1.readlines()
tav1 = random.choice(name1).strip()

tavern2 = open('tavnames2.txt')
name2 = tavern2.readlines()
tav2 = random.choice(name2).strip()

tavern_name = 'The {} {}'.format(tav1, tav2)

print(tavern_name)

A way to get rid of the newlines is to read the whole file and use splitlines() : (see Reading a file without newlines )

tavern1 = open('tavnames1.txt', 'r')
name1 = tavern1.read().splitlines()

To pick a random item of the list name1 you can use tav1 = random.choice(name1) (see https://docs.python.org/3.6/library/random.html#random.choice ).

Take the first value from tav1 and tav2 , by doing tav1[0].strip() . The .strip() takes care of the \\n .

By taking a random.sample , you get a list of values. Because you take just one sample, you get a list with just one item in it, in your example "Young". But, it is in a list, so it is more like ["Young"] . To access only "Young" , take the first (and only) item from the list, by saying tav1[0] .

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