Home > Enterprise >  How to count chars in string but with newline as one character
How to count chars in string but with newline as one character

Time:12-25

I try to count characters in result of textarea. It can contains many lines.

text = '1
2
3'

if I use len(text) the result is 7, because it counts each newline as two characters (which is quite possible CR LF are two characters). But I want to count it as one character - is there any method or I have to count newlines and substract it?

CodePudding user response:

For now I use:

number_of_chars = len(text)-text.count('\r')

CodePudding user response:

You can't include nextline inside single quotes. It'll give you an error inside the interpreter.

You can use tripple quotes instead.

And as for the question itself, here is your answer:

text = '''1
2
3'''

count_letter = text.split('\n')

no_of_chars_with_nextline = len(count_letter)   (len(count_letter)-1)

print(no_of_chars_with_nextline)

Answer:

5
  • Related