471,353 Members | 1,739 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,353 software developers and data experts.

using .split ( )?

Thekid
145 100+
Hi,

Is there a way for me to use .split without having to constantly change my code to adapt to a string? Here's a sample:

Expand|Select|Wrap|Line Numbers
  1.  
  2. s =input("Enter string:")
  3. #say string entered is: "2/3/4/5/6"
  4. x=s.split("/")
  5. print x
  6.  
  7.  
That works fine but how can I get it to handle any string that is entered if on the next run it looks like one of these:

"2#3#4#5#6"
or
"45%65%74%2%9%"
etc.....
Oct 26 '07 #1
3 3953
oler1s
671 Expert 512MB
There's a couple of ways. The first is to have the user specify what the delimiting value is. This is the most straightforward, and probably the best way. The second is to take a guess, by manipulating the string yourself, and seeing what the pattern might look like.
Oct 26 '07 #2
bvdet
2,851 Expert Mod 2GB
You can use the re module. Try this:
Expand|Select|Wrap|Line Numbers
  1. import re
  2.  
  3. s = '1/2/3/4/5'
  4. s1 = '1#2#3#4#5'
  5. s2 = '1^2^3^4^5'
  6.  
  7. patt = '[/^#]'
  8.  
  9. print re.split(patt, s)
  10. print re.split(patt, s1)
  11. print re.split(patt, s2)
Oct 26 '07 #3
Thekid
145 100+
You can use the re module. Try this:
Expand|Select|Wrap|Line Numbers
  1. import re
  2.  
  3. s = '1/2/3/4/5'
  4. s1 = '1#2#3#4#5'
  5. s2 = '1^2^3^4^5'
  6.  
  7. patt = '[/^#]'
  8.  
  9. print re.split(patt, s)
  10. print re.split(patt, s1)
  11. print re.split(patt, s2)
Oler1s, thank you for your reply but this is more of what I was looking for:

Expand|Select|Wrap|Line Numbers
  1.  
  2. import re
  3.  
  4. patt = '[/&$^]'
  5. s = input("Enter string:")
  6. print re.split(patt,s)
  7.  
  8.  
Works good like that! Thanks Bvdet!
Oct 26 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by Vamsi | last post: by
1 post views Thread by ratnakarp | last post: by
reply views Thread by mookie | last post: by
5 posts views Thread by Michael Sperlle | last post: by
1 post views Thread by Richard Harter | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.