Split a string, loop through it character by character, and replace specific ones?

for loop
iterate through characters in a string js
iterate over letters in string javascript
how to iterate through each character in a string javascript
iterate string javascript
javascript loop chars in string
replace character in string
jquery split each character in string

I'm working on an assignment and have gotten stuck on a particular task. I need to write two functions that do similar things. The first needs to correct capitalization at the beginning of a sentence, and count when this is done. I've tried the below code:

def fix_capitalization(usrStr):
count = 0
fixStr = usrStr.split('.')
for sentence in fixStr:
    if sentence[0].islower():
        sentence[0].upper()
        count += 1
print('Number of letters capitalized: %d' % count)
print('Edited text: %s' % fixStr)

Bu receive an out of range error. I'm getting an "Index out of range error" and am not sure why. Should't sentence[0] simply reference the first character in that particular string in the list?

I also need to replace certain characters with others, as shown below:

def  replace_punctuation(usrStr):
    s = list(usrStr)
    exclamationCount = 0
    semicolonCount = 0
    for sentence in s:
        for i in sentence:
            if i == '!':
                sentence[i] = '.'
                exclamationCount += 1
            if i == ';':
                sentence[i] = ','
                semicolonCount += 1
    newStr = ''.join(s)
    print(newStr)
    print(semicolonCount)
    print(exclamationCount)

But I'm struggling to figure out how to actually do the replacing once the character is found. Where am I going wrong here?

Thank you in advance for any help!

I would use str.capitalize over str.upper on one character. It also works correctly on empty strings. The other major improvement would be to use enumerate to also track the index as you iterate over the list:

def fix_capitalization(s):
    sentences = [sentence.strip() for sentence in s.split('.')]
    count = 0
    for index, sentence in enumerate(sentences):
        capitalized = sentence.capitalize()
        if capitalized != sentence:
            count += 1
            sentences[index] = capitalized
    result = '. '.join(sentences)
    return result, count

You can take a similar approach to replacing punctuation:

replacements = {'!': '.', ';': ','}

def replace_punctuation(s):
    l = list(s)
    counts = dict.fromkeys(replacements, 0)
    for index, item in enumerate(l):
        if item in replacements:
            l[index] = replacements[item]
            counts[item] += 1
    print("Replacement counts:")
    for k, v in counts.items():
        print("{} {:>5}".format(k, v))
    return ''.join(l)

How can I iterate over the characters in a string, and change them , You can iterate over each of the characters in the text like this for (var x = 0; x < text.length; x++) { var c = text.charAt(x); //Add code here to do the  Iterate over characters of a string in Python In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over characters of a string in Python.

There are better ways to do these things but I'll try to change your code minimally so you will learn something. The first function's issue is that when you split the sentence like "Hello." there will be two sentences in your fixStr list that the last one is an empty string; so the first index of an empty string is out of range. fix it by doing this.

def fix_capitalization(usrStr):
    count = 0
    fixStr = usrStr.split('.')
    for sentence in fixStr:
        # changed line
        if sentence != "":
            sentence[0].upper()
            count += 1
    print('Number of letters capitalized: %d' % count)
    print('Edited text: %s' % fixStr)

In second snippet you are trying to write, when you pass a string to list() you get a list of characters of that string. So all you need to do is to iterate over the elements of the list and replace them and after that get string from the list.

def  replace_punctuation(usrStr):
    newStr = ""
    s = list(usrStr)
    exclamationCount = 0
    semicolonCount = 0
    for c in s:
        if c == '!':
            c = '.'
            exclamationCount += 1
        if c == ';':
            c = ','
            semicolonCount += 1
        newStr = newStr + c
    print(newStr)
    print(semicolonCount)
    print(exclamationCount)

Hope I helped!

ActionScript Cookbook, ActionScript Cookbook, Alternatively, use String split() with the empty string as the delimiter to split the an array of all the characters, then use a for statement to loop through the array. Discussion The simplest way to process each character of a string is to use a string. Recently, I needed to insert some data into a simple table, using Microsoft SQL Server and the data was coma delimited.. Solution. Here is a simple how to split a coma delimited string and loop the values:

Python has a nice build in function for this

for str in list:
    new_str = str.replace('!', '.').replace(';', ',')

You can write a oneliner to get a new list

new_list = [str.replace('!', '.').replace(';', ',') for str in list]

You also could go for the split/join method

new_str = '.'.join(str.split('!'))
new_str = ','.join(str.split(';'))

To count capitalized letters you could do

result = len([cap for cap in str if str(cap).isupper()])

And to capitalize them words just use the

str.capitalize()

Hope this works out for you

ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex , Alternatively, use String split() with the empty string as the delimiter to split the an array of all the characters, then use a for statement to loop through the array. Discussion The simplest way to process each character of a string is to use a string. for (var i = 0; i < myString.length; it #) { /* Output each character, one at a time. Way back when during our Siemens LCR days we had to limit the number of characters in OBX.5 to a length of 75. That was back when we had eGate. Now I need to do the reversal of that and take loop through a string length and split the string up into multiple OBX or NTE based on a certain length.

From VBA to VSTO: Is Excel's New Engine for You?, remove characters or words instead of replacing them simply use the empty string as at a Time Problem You want to retrieve one character at a time from a string. Alternatively, use String.split() with the empty string as the delimiter to split the of all the characters, and then use afor statement to loop through the array. will loop through each letter in the string. Loop Through Each Character in a String – Alternative. Read Every Character in a String: This example reads every character in a string from left to right and returns the result in a message box. It makes use of the Mid function.

TypeScript High Performance, IsDigit(string, n) acts on the nth character of the specified string. all the characters in a string, starting at index 0, so you can loop through all its Replace() – do not return a new, separate string but act directly on the string they are applied to. Next we use Regex.Split to separate a string based on multiple characters. Regex.Split can also handle metacharacters, not just values we specify directly. Argument 1: The first argument to Regex.Split is the string we wish to split. Regex.Split is a static method.

How to iterate over words of String in Python? – 2 Python Examples, We loop over the base string and perform this replacement a total of 50,000 times​. Let's take a look at the following replacement option code snippet: baseString.​split(' the string into substrings, as specified by an optional splitter character. The strrep function does not find empty character vectors or empty strings for replacement. That is, when str and old both contain the empty character vector ('') or the empty string(""), strrep does not replace empty character vectors or strings with the contents of new.

Comments
  • Are you allowed to use the built-in function string.replace()?
  • @KuboMD I am and have tried that but have the same issue in referencing the particular character. Any idea how that could be done?
  • By the way - sentence[0].upper() doesn't do anything. You need to make a second string to add the letters back into. .upper() needs to be assigned to a variable; and you can't assign it to itself due to the nature of a string being immutable.
  • '5.'.split('.') results in ['5', ''] can you see the issue in trying to access 0 index without an empty-string check?
  • As long as you're working from the left, you can limit the # of replacements so it only replaces the one character that you want to delete. string.replace("old char", "new char", 1)