简体   繁体   中英

ValueError: invalid literal for int() with base 10

I am a beginner in python. I came across this question in codewars.

Jaden is known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word. Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.

Example :

Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"

Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"

This is my attempt (I am supposed to code using a function)

def toJadenCase(string):
    l = len(string)
    for i in range(0,l):
        if string[i] == ' ':
            y = string[i]
            string[i+1] = chr(int(y)-32)
    return srting
s = raw_input()
print toJadenCase(s)

When run, the following errors showed up

How can mirrors be real if our eyes aren't real  (this is the input string)
Traceback (most recent call last):
  File "jaden_smith.py", line 9, in <module>
    print toJadenCase(s)
  File "jaden_smith.py", line 6, in toJadenCase
    string[i+1] = chr(int(y)-32)
ValueError: invalid literal for int() with base 10: ''

I couldn't understand these errors even after google-ing it. Any help would be appreciated. I would also be great if other errors in my code are highlighted and a better code is suggested.

Thanks in advance :D

As Goodies points out, string should not be used as a variable name

Following the Zen of Python , this is technically a function that does exactly what you're trying to achieve:

def toJadenCase(quote):
    return quote.title()

Edit:

Revised version to deal with apostrophes:

import string

def toJadenCase(quote):
    return string.capwords(quote)

First you have to understand that strings are immutable, so you cannot set a single character inside a string, but build a new string from the old one and replace the old one (this can be usually done still in one pass so it's not a big complication). Second, for most of these kind of operations, it is much better to use the methods of the string object itself, rather than redo everything from scratch.

Said that, there is still some complication with the question, but a function that does what you want is in the module string:

import string
s="How can mirrors be real if our eyes aren't real"
newstring=string.capwords(s)

If you prefer (why?!) a DIY solution (using string methods):

newstring=' '.join([ss.capitalize() for ss in s.split()])

Note that using split without argument splits the string on any whitespace (eg tabs etc.), that I think is the desired behavior.

If you want to do this without using a function that already exists, this is how I would do it and I'll explain everything:

Assuming you get a string with ONLY text based words and all words start with a character*

def toJadenCase(string):
    words = string.strip().split() 
# This first strips all empty spaces around the words in the text and then splits the string by spaces (default) otherwise you can add a character inside split in order to split it at the character.  This returns a list of words in the sentence.
    li = [] # initialize empty list
    for word in words:
        word = chr(ord(word[0])-32) + word[1:] 
# So there's a couple of things going on here.  
# I could use .upper() to upper case something (like word[0].upper() + word[1:] 
# in order to get it but I wanted to do it without the use of that.  
# That being said, ord just figures out the ascii number and subtracting
# 32 makes it uppercase.  chr changes it back to a string.  
# Then it can be concatenated to the rest of the word.  
# Strings can be treated as lists in python so word[0] and word[1:] works
Also, word[1:] just means from the 1st index to the end.
    li.append(word) # this appends the word to the list
    return ' '.join(li) # this joins all of the words in the list with a space

Now, if you want something a lot more concise (you can use .capitalize()):

def toJadenCaseShort(string):
    return ' '.join([x.capitalize() for x in string.strip().split()])

which returns:

>>> abc("hello my friends")
'Hello My Friends'

Basically what it does is it uses list comprehension to strip and then split the words, capitalizes them, and then joins them with spaces!

Of course, you could just use string.title() as mark s. says but what's the fun in that? :)

Here is the answer that passed for me

 import string def toJadenCase(str): quote = string.capwords(str) return quote #Do not use print(quote) as it adds spaces 

def toJadenCase(str): quote = string.capwords(str) return quote #Do not use print(quote) as it adds spaces

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM