• Register
2 votes
26 views

Problem:

Hello good soul,

I have passed a successful year in java programming and now started learning python very recently. In java, I used the array.length function to find out the string length. What is the best practice in python to count a String length?

Thanks for your answer.
I really appreciate your effort.

12 7 7
15,250 points

1 Answer

2 votes

Solution:

Hello Gavin,

I am aware that you have a strong command of programming as per your saying. In python, we can do the same thing in different ways.

I am going to introduce you to the function count().  It is the most convenient method in Python to get the occurrence of any element in any container. This is easy to code and remember and hence quite popular.

# Python3 code to demonstrate  
# occurrence frequency using  

# initializing string  
my_str = "I Love Python"
  
# using count() to get count  
counter = my_str.count('o') 
  
# printing result  
print ("Count of o in I Love Python is : "
                           +  str(counter))

The above program will look for the ‘O’ in our my_str and the output would be:

Count of o in I Love Python is : 2

 

13 9 6
94,240 points

Related questions

0 votes
1 answer 19 views
19 views
Problem: I was trying to remove all occurrences of a character in a string python but I failed. The code I wrote is: def DeletChar(e, b) : counts = e.count(b) e = list(e) while counts : e.remove(b) counts -= 1 print(e) if __name__ == '__main__' : e = "geeksforgeeks" DeletChar(e,'g') The output ... e', 'k', 's', 'f', 'o', 'r', 'e', 'e', 'k', 's'] how to solve this problem I am a newbee please help
asked Mar 22 LizzyM 6.1k points
0 votes
1 answer 22 views
22 views
How to get the number from the occurences of individual characters Supose the string is: x = 'cdfghcfonccn' How can i solve this problem.
asked Mar 10 LizzyM 6.1k points
0 votes
1 answer 2 views
2 views
Problem: Hello! How can I count the number of characters in a string automatically through c#?
asked Oct 11 Sheeza 2.9k points
1 vote
1 answer 17 views
17 views
Problem: I tried to count occurrences of individual character of string using python. So I wrote this program for the string: a = 'yanwawny' The program: ​​​string = 'yanwawny' ​dict((letter, string.count(letter)) for letter in set(a) But it throws the error message: File "main.py", line 1 ​a = 'yanwawny' ^ SyntaxError: invalid character in identifier What to do to solve this thing?
asked May 4 samhaz 5k points
2 votes
1 answer 17 views
17 views
Problem: Hello guys, I hope you all are doing well. I am learning java programming in my school. My teacher taught us many things about the string in the last class and gave a problem to solve. I tried to solve the problem but couldn’t make it happen so far. ... problem I’d be grateful to him/her. So, my problem is: find all occurrences of a substring in a string java Thanks, mate.
asked Mar 25 Gavin 15.3k points