strings

strings

str(123)                      <--converting numbers to string
int("-123")                   <--converting strings to numbers
print ("abc"+str(23))         <--abc123 (if you need to concatenate numbers and characters)

len("abcdef")                 <--displays the length of a string

s = "abcdefghi"
s.find("def")                 <--finds the position of "def" in given string (it will display 3)
Note that the character positions start at 0, so a position of 3 means the fourth character in the string.
If the string you’re looking for doesn’t exist in the string being searched, then find returns the value -1.

s[1:5]                        <--cut out a section (it will display "bcde")
Note that the character positions start at 0, so a position of 1 means the second character in the string and 5 means the sixth, but the character range is exclusive at the high end, so the letter f is not included in this example.

s[:5]                         <--display string from start to the 5th caracter
s[5:]                         <--display string from the 5th caracter to the end
s[-3:]                        <--display the last 3 characters

s.replace("b", "xyz")         <--replace "b" with "xyz"
s.upper()                     <--converts to uppercase (it will not modify s, it will be still lower case)
s.lower()                     <--converts to lowercase (same as above)
s=s.upper()                   <--s will be uppercase now

==============================

If you need to convert a string of words separated by some character into an array of strings with each string in the array being one of the words, use the split Python string function. The command split with no parameters separates the words out of a string into individual elements of an array:
"abc def ghi".split()
['abc', 'def', 'ghi']

If you supply split with a parameter, then it will split the string using the parameter as a separator. For example:
"abc--de--ghi".split('--')
['abc', 'de', 'ghi']

No comments:

Post a Comment