Last modified: March 01, 2020

python length string

example 1: count length with whitespace

1
2
3
x = "hello world"
str_len = len(x)
print(str_len)

output

1
11

#whitespace will also count with characters
so in this example we have 10 characters + 1 whitespace = 11

example 2: count length without whitespace

to do this we need first replace whitespace by "" then count the length of string

1
2
3
4
5
6
7
8
9
#str
x = "hello world"
#replace
z = x.replace(" ", "")

#count length
str_length = len(z)

print(str_length)

output

1
10