开发者

How do you create a n by n box of X's in python using string manipulation? (eg. replace, count, find, len, etc.)

开发者 https://www.devze.com 2023-04-07 01:47 出处:网络
Get a number from the user (n) and create an n x n box of \"开发者_开发知识库X\"es on the screen. Without using loops yet.

Get a number from the user (n) and create an n x n box of "开发者_开发知识库X"es on the screen. Without using loops yet. e.g. If they entered 12:

XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX

The point of this assignment is to use string manipulation to create this box. I can do it with a loop but I'm not sure how to do it with just strings. Can anyone help me out?


You can "multiply" strings. For example, 'x' * 3 gives you xxx. So:

size = int(input())  # convert whatever you have to int
print(size * (size * 'X' + '\n'))  # print the whole thing

This isn't very intuitive (very few languages will let you do that), but getting the input should be straightforward enough.


You could also use join:

print('\n'.join(['X'*12]*12))


I would do:

size = int(raw_input())
print ('X' * size + '\n') * size,

In 3.x, that would be

size = int(input())
print(('X' * size + '\n') * size, end='')
0

精彩评论

暂无评论...
验证码 换一张
取 消