0

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.

user1630350
  • 79
  • 3
  • 11
  • Take the first value from `tav1` and `tav2`, by doing `tav1[0].strip()`. The `.strip()` takes care of the `\n`. – Mathias711 Jan 02 '17 at 09:37
  • Sorry I'm not overly fluent in python, can you elaborate a bit more please. – user1630350 Jan 02 '17 at 09:38
  • `sample()` always return list - even if it has one element - so `tav1` and `tav2` are lists and you use `str()` to convert it to text. Use `tav1 = tav1[0]` or `random.choice(name1)` to get only one element. – furas Jan 02 '17 at 09:40

3 Answers3

3

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)
furas
  • 134,197
  • 12
  • 106
  • 148
3

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).

Community
  • 1
  • 1
jim
  • 311
  • 3
  • 13
0

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].

Mathias711
  • 6,568
  • 4
  • 41
  • 58