Python Forum
Replacing string values with count
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replacing string values with count
#1
my question here

Define a function that takes a string and replaces each character with a string of the number of times that letter occurs in the word.
'Hello' -> '11221'
Ignore capitalization, so if a word has an 'H' and an 'h' the count would be more than 1.

import collections
a = 'Hello'
letters = collections.Counter(a.lower())

dict(letters)
Reply
#2
So get the string and for each letter get the value from the dict. Then join all values in a new string.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
(Jul-19-2017, 02:17 AM)tomhuang Wrote: my question here

Define a function that takes a string and replaces each character with a string of the number of times that letter occurs in the word.
'Hello' -> '11221'
Ignore capitalization, so if a word has an 'H' and an 'h' the count would be more than 1.

import collections
a = 'Hello'
letters = collections.Counter(a.lower())

dict(letters)

Looks like you've got it.  So what's the problem?

If you don't want to use a module, you can always roll your own:
>>> val = "Hello"
>>> "".join(map(str, map(sum, ((1 for ch in val if ch.lower()==pos.lower()) for pos in val))))
'11221'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Count occurences in a string and add to a list using loops Leyo 4 1,668 Mar-11-2022, 03:52 PM
Last Post: Leyo
  Replacing a few characters of a specified character but not all of them from a string fatherted99 7 3,192 Aug-13-2020, 09:08 AM
Last Post: fatherted99
  Count Letters in a Sentence (without using the Count Function) bhill 3 5,165 Jun-19-2018, 02:52 AM
Last Post: bhill

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020