python3 remove space from print

2020-05-06 14:14发布

I've got some simple python loop through a name to create a list of devices:

for i in range(18):
print("sfo-router",(i))

The problem is it prints with a space between the name and the number:

sforouter 1
sforouter 2
sforouter 3
sforouter 4

I'm just learning the ropes of python, so not sure how I can remove that space. How can it be done? thanks.

3条回答
Animai°情兽
2楼-- · 2020-05-06 14:53

I'm new at python as well, and a quick google search did this one:

Just use str.replace():

string = 'hey man'
string.replace(" ","")
# String is now 'heyman'

Source: Python remove all whitespace in a string

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-05-06 15:12

Use format:

for i in range(18):
    print("sfo-router{}".format(i))
查看更多
疯言疯语
4楼-- · 2020-05-06 15:16

Change the sep parameter so that print doesn't implicitly insert a space:

for i in range(18):
    print("sfo-router",(i), sep='')

Alternatively, you can convert your number to a string with str and concatenate:

for i in range(18):
    print("sfo-router" + str(i))

Outputs: (in both cases)

sfo-router0
sfo-router1
sfo-router2
sfo-router3
sfo-router4
sfo-router5
...
查看更多
登录 后发表回答