Python tutorial- string manipulation

String manipulation

A string can be treated as a tuple. However, Python provides some useful methods to manipulate strings.

lower() and upper() methods:

To make a string contain only lower case letters, you can use lower() method. In contrast, upper() method converts all letters of a string to upper case letters.

>>> st='Hello World'
>>> st.lower()
'hello world'
>>> st.upper()

replace() and find() methods:

The replace() method will replace an old substring with a new substring. This method will not modify the string. It only returns a new string with the replacement.
>>> st.replace('World','Mr.Vibol')
'Hello Mr.Vibol'
>>> st
'Hello World'
To find a substring in a string, you can use find() method. The find() method will return a index of the substring. If the substring is not in the string, it will return -1.
>>> st.find('or')
>>> st.find(',')

startswith() and endswith() methods:

You test whether a string starts with or ends with a substring. These methods return True if the string starts with or ends with the substring, otherwise False.
>>> st.startswith('da')
>>> st.startswith('He')
>>> st.endswith('ol')
>>>  split() and join() methods:
The split() method will split a string by a separator.
>>> fullname=raw_input("Please enter your name separated by space:")
Please enter your name separated by space:Yuk Sovandara
>>> fname=fullname.split(' ')[0]
>>> fname
>>> lname=fullname.split(' ')[1]
>>> lname
To join substrings together to generate a string, you can use join() method:
>>> lst=['1','2','3','4','5']
>>> '+'.join(lst)
  Note: the first substring is treated as a separator in joining operation.

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.