Abby Lacson
Abby Lacson

Reputation: 21

Splitting a string of numbers

I was wondering how i cant split this string for a game i'm assigned. The player is supposed to input an x and y value for a 60x15 grid.

answer = input('enter an x and y coordinate with a space between')

ill make my x equal to 30 and my y equal to 7

playerAnswer = []
answer = '30 7'
answer.split(' ')
playerAnswer.append((player[0], player[1]))

when I do this i get playerAnswer to be ['3', '0'] is there any way to make the playerAnswer to become ['30', '0']?

Upvotes: 1

Views: 74

Answers (3)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

Most pythonic way to achieve this is:

>>> x, y = map(int, input('enter an x and y coordinate with a space between').split())
>>> x
30
>>> y
7 

Now coming to the issue with your code:

playerAnswer.append((player[0], player[1]))

replace player with answer as you are storing the splitted values in answer variable (also I do not see any player variable in the code you mentioned, so I am not sure what it stores. But I am sure you don not need that). Below lines should work fine.

playerAnswer.append((answer[0], answer[1]))

Also, I do not think you need 30 and 7 as str. For converting it into int, I am using map() function.

Upvotes: 0

Alexander
Alexander

Reputation: 109756

a, b = [int(i) for i in answer.split()]
>>> a
30
>>> b
7

Or, if you really want text:

playerAnswer = []
playerAnswer.append(tuple(i for i in answer.split()))

>>> playerAnswer
[('30', '9')]

Upvotes: 0

timgeb
timgeb

Reputation: 78800

The problem is that you are not using the return value of split. str.split does not modify a string in place (strings are actually immutable), but returns a list.

Demo:

>>> answer = '30 7'
>>> answer_split = answer.split(' ')
>>> answer
'30 7'
>>> answer_split
['30', '7']
>>> answer_split[0]
'30'
>>> answer_split[1]
'7'

In case you want actual integers, you can do:

>>> answer_split = [int(x) for x in answer.split(' ')]
>>> answer_split
[30, 7]

I am not exactly sure why you are indexing into player instead of the result of split when appending to playerAnswer, so that is likely another bug.

Note: if you just want to split by any whitespace, you can omit the argument ' ' to split.

Upvotes: 1

Related Questions