Solved

Python Strings, indexing

Posted on 2011-09-15
5
369 Views
Last Modified: 2012-06-27
I am trying to print certain parts of a string.
I think i need to use indexing like print(string[0:midChar] but its not working

error:

Traceback (most recent call last):
  File "C:/Python27/joe", line 6, in <module>
    print str[0:midChar]
TypeError: slice indices must be integers or None or have an __index__ method
0
Comment
Question by:Stephen1991
  • 2
  • 2
5 Comments
 
LVL 5

Accepted Solution

by:
-Richard- earned 20 total points
ID: 36543436
print str[0:len(str)/2]
midChar is the actual midde character of the string, and therefore is of type character.  It is not the index of the middle character, which would be an integer, which is required by the bracket notation for indexing into strings.
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 36543468
Remember though, the second value in

stringName[ start:finish ]

identifies the first character that won't be returned...

For example:
>>> stringName = '0123456789'
>>> stringName[ 2:5 ]
'234'
>>>

Open in new window

0
 

Author Comment

by:Stephen1991
ID: 36543482
Okay. Thank you very much.


to print the rest of the string after the middle is this okay:

print word[(len(word)/2)+1:]
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 36543495
yup
>>> word = 'Now is the time for all good men to come to the aid of their country.'
>>> print word[(len(word)/2)+1:]
 come to the aid of their country.
>>>

Open in new window

0
 

Author Comment

by:Stephen1991
ID: 36543532
Nicee.  Thanks.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Installing Python 2.7.3 version on Windows operating system For installing Python first we need to download Python's latest version from URL" www.python.org " You can also get information on Python scripting language from the above mentioned we…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question